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

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

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

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

  const [orderCompany, setOrderCompany] = useState<BusinessAPI.OrderCompany>();

  // 当 orderVO 变化时，更新默认显示的公司信息
  useEffect(() => {
    if (orderVO.orderCompany) {
      setOrderCompany(orderVO.orderCompany);
    }
  }, [orderVO]);

  // 处理公司账户选择完成事件
  const handleCompanySelect = (companyVO: BusinessAPI.CompanyVO) => {
    if (readOnly) return;

    // 构造新的 orderCompany 对象
    const newOrderCompany: BusinessAPI.OrderCompany = {
      orderCompanyId: orderVO.orderCompany?.orderCompanyId || "",
      orderId: orderVO.orderId,
      companyId: companyVO.companyId,
      shortName: companyVO?.shortName || "",
      fullName: companyVO?.fullName || "",
      taxNumber: companyVO?.taxNumber || "",
      contactPerson: companyVO?.contactPerson || "",
      contactPhone: companyVO?.contactPhone || "",
      address: companyVO?.address || "",
    };

    // 更新 orderCompany 状态
    setOrderCompany(newOrderCompany);

    // 构造新的 orderVO 对象
    const newOrderVO = {
      ...orderVO,
      orderCompany: newOrderCompany,
    };

    // 通知父组件 orderVO 已更改
    onChange?.(newOrderVO);
  };

  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 text-sm font-medium">
            公司名称
          </View>
          <View className="text-neutral-darkest text-sm">
            {orderCompany?.fullName || "请先选择销售方"}
          </View>
        </View>
      </View>

      {!readOnly && (
        <View className="flex justify-center">
          <CompanyPicker
            onFinish={handleCompanySelect}
            trigger={
              <View className={"flex-1"}>
                <Button
                  icon={<Icon name="pen-to-square" size={18} />}
                  size={"large"}
                  type="primary"
                  fill="outline"
                  block
                >
                  {orderCompany ? "修改我方入账公司" : "选择我方入账公司"}
                </Button>
              </View>
            }
          />
        </View>
      )}
    </View>
  );
});
