import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { View } from "@tarojs/components";
import { DealerPicker, Icon } from "@/components";
import { Button } from "@nutui/nutui-react-taro";

export interface DealerInfoSectionRef {
  validateForm: () => string | null;
}

export default forwardRef<
  DealerInfoSectionRef,
  {
    orderVO: BusinessAPI.OrderVO;
    onChange?: (orderDealer: BusinessAPI.OrderVO) => void;
    readOnly?: boolean;
  }
>((props, ref) => {
  const { orderVO, onChange, readOnly } = props;

  // 暴露 validateForm 方法
  useImperativeHandle(ref, () => ({
    validateForm: () => {
      // 校验经销商
      if (!orderVO?.orderDealer?.dealerId) {
        return "请选择经销商";
      }
      return null;
    },
  }));

  const [orderDealer, setOrderDealer] = useState<BusinessAPI.OrderDealer>();

  // 添加经销商名称状态（用于只有名称没有ID的情况）
  const [dealerNameOnly, setDealerNameOnly] = useState<string>();

  // 初始化默认值
  useEffect(() => {
    if (orderVO.orderDealer) {
      setOrderDealer(orderVO.orderDealer);
    } else if (orderVO.orderVehicle?.dealerName && !orderVO.orderDealer) {
      // 只有经销商名称，没有完整的经销商信息
      setDealerNameOnly(orderVO.orderVehicle.dealerName);
    }
  }, [orderVO]);

  // 处理经销商选择完成事件
  const handleDealerSelect = (dealerVO: BusinessAPI.DealerVO) => {
    if (readOnly) return;

    const newOrderDealer: BusinessAPI.OrderDealer = {
      ...dealerVO,
    };

    setOrderDealer(newOrderDealer);
    // 构造新的 orderVO 对象
    const newOrderVO = {
      ...orderVO,
      orderDealer: newOrderDealer,
    };
    onChange?.(newOrderVO);
    setDealerNameOnly(undefined);
  };

  return (
    <View className={"flex flex-col gap-2.5"}>
      <View className="bg-primary/3 rounded-lg border-b border-gray-100 p-2.5">
        <View className="flex flex-row items-center justify-between">
          <View className="text-neutral-dark flex-shrink-0 text-sm">
            经销商名称
          </View>
          <View className="text-neutral-darkest text-sm font-medium">
            {orderDealer?.shortName || "请先选择经销商"}
          </View>
        </View>

        {dealerNameOnly && (
          <View className="text-xs text-orange-500">
            <View>检测到当前经销商“{dealerNameOnly}”信息未创建</View>
            <View className="mt-1">• 请前往电脑端创建经销商信息后再选择</View>
            <View>• 或选择系统中已存在的其他经销商</View>
          </View>
        )}
      </View>

      {!readOnly && (
        <DealerPicker
          enableManualInput={false}
          onFinish={(dealer) => {
            handleDealerSelect(dealer);
          }}
          trigger={
            <View className={"flex-1"}>
              <Button
                icon={<Icon name="pen-to-square" size={18} />}
                size={"large"}
                type="primary"
                fill="outline"
                block
              >
                {orderDealer ? "修改下游经销商" : "选择下游经销商"}
              </Button>
            </View>
          }
        />
      )}
    </View>
  );
});
