import { forwardRef, useImperativeHandle, useState } from "react";
import { Text, View } from "@tarojs/components";
import {
  Button,
  DatePicker,
  Input,
  PickerOption,
  Popup,
  Table,
  TextArea,
  Toast,
} from "@nutui/nutui-react-taro";
import { DealerWarehousePicker, Icon } from "@/components";
import dayjs from "dayjs";

interface Step1FormProps {
  orderShipVO: any;
  setOrderShipVO: (value: any) => void;
}

export interface Step1FormRef {
  validateForm: () => boolean;
}

const Step1Form = forwardRef<Step1FormRef, Step1FormProps>((props, ref) => {
  const { orderShipVO, setOrderShipVO } = props;

  // 当天和未来10天
  const startDate = new Date();
  const endDate = new Date(startDate.getTime() + 86400000 * 10);
  const [show, setShow] = useState(false);

  // 添加商品弹窗控制
  const [showAddGoodsPopup, setShowAddGoodsPopup] = useState(false);

  // 商品表单数据
  const [goodsFormData, setGoodsFormData] = useState({
    productName: "",
    origin: "",
    spec: "",
    unit: "",
    quantity: "",
    weight: "",
    price: "",
  });

  const formatter = (type: string, option: PickerOption) => {
    switch (type) {
      case "year":
        option.label += "年";
        break;
      case "month":
        option.label += "月";
        break;
      case "day":
        option.label += "日";
        break;
      case "hour":
        option.label += "时";
        break;
      case "minute":
        option.label += "分";
        break;
      default:
        break;
    }
    return option;
  };

  // 表单错误状态
  const [formErrors, setFormErrors] = useState<{
    warehouse?: boolean;
    estimatedArrivalDate?: boolean;
  }>({});

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    validateForm,
  }));

  // 暴露方法给父组件
  const validateForm = () => {
    const errors: any = {};
    let hasErrors = false;

    // 检查收货仓库是否已填写
    if (!orderShipVO?.warehouse) {
      errors.warehouse = true;
      hasErrors = true;
      Toast.show("toast", {
        icon: "fail",
        title: "请选择收货仓库",
      });
    }

    setFormErrors(errors);
    return !hasErrors;
  };

  // 处理商品表单字段变化
  const handleGoodsFormChange = (field: string, value: string) => {
    setGoodsFormData((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  // 重置商品表单
  const resetGoodsForm = () => {
    setGoodsFormData({
      productName: "",
      origin: "",
      spec: "",
      unit: "",
      quantity: "",
      weight: "",
      price: "",
    });
  };

  // 提交商品表单
  const submitGoodsForm = () => {
    // 这里可以添加表单验证逻辑
    console.log("添加商品:", goodsFormData);
    // 关闭弹窗并重置表单
    setShowAddGoodsPopup(false);
    resetGoodsForm();
  };

  return (
    <View className="flex flex-col gap-2.5 rounded-lg bg-white">
      <View className="flex flex-col gap-2.5">
        <View className="border-b border-b-gray-200 pb-2.5">
          <Text className="text-base font-semibold">基础信息</Text>
        </View>

        {/* 收货仓库 */}
        <View>
          <View className="mb-1 block text-sm font-normal text-[#000000]">
            收货仓库 <Text className="text-red-500">*</Text>
          </View>
          <View
            className={`flex h-10 w-full items-center rounded-md ${formErrors.warehouse ? "border-4 border-red-500" : "border-4 border-gray-300"}`}
          >
            <DealerWarehousePicker
              dealerId={orderShipVO?.dealerId}
              onFinish={(dealerWarehouseVO: BusinessAPI.DealerWarehouseVO) => {
                setOrderShipVO((prev: any) => {
                  return {
                    ...prev!,
                    warehouseId: dealerWarehouseVO.warehouseId,
                    warehouseName: dealerWarehouseVO.name,
                  };
                });
              }}
              trigger={
                <>
                  <View className={"text-sm"}>
                    {orderShipVO?.warehouseName || "选择收货仓库"}
                  </View>
                  <Icon name={"chevron-down"} />
                </>
              }
            />
          </View>

          {formErrors.warehouse && (
            <View className="mt-1 text-xs text-red-500">请选择收货仓库</View>
          )}
        </View>

        {/* 预计到仓时间 */}
        <View>
          <View className="mb-1 block text-sm font-normal text-[#000000]">
            预计到仓时间
          </View>
          <View
            className={`flex h-10 w-full items-center rounded-md ${formErrors.estimatedArrivalDate ? "border-4 border-red-500" : "border-4 border-gray-300"}`}
          >
            <View
              className={
                "flex flex-1 flex-row items-center justify-between px-5"
              }
              style={{
                color: "var(--nutui-color-title, #1a1a1a)",
              }}
              onClick={() => setShow(true)}
            >
              <View className={"text-sm"}>
                {orderShipVO?.estimatedArrivalDate
                  ? dayjs(orderShipVO?.estimatedArrivalDate).format(
                      "YYYY年MM月DD日",
                    )
                  : "请选择预计到仓时间"}
              </View>
              <Icon name={"chevron-down"} />
            </View>
            <DatePicker
              title="发货时间选择"
              type="date"
              startDate={startDate}
              endDate={endDate}
              visible={show}
              defaultValue={new Date()}
              formatter={formatter}
              onClose={() => setShow(false)}
              onConfirm={(_, values) => {
                // 选择日期后清除错误状态
                if (formErrors.estimatedArrivalDate) {
                  setFormErrors((prev) => ({
                    ...prev,
                    estimatedArrivalDate: false,
                  }));
                }

                setOrderShipVO((prev: any) => {
                  return {
                    ...prev!,
                    estimatedArrivalDate: dayjs(values.join("-")).format(
                      "YYYY-MM-DD",
                    ),
                  };
                });
              }}
            />
          </View>
        </View>

        {/* 备注 */}
        <View>
          <View className="mb-1 block text-sm font-normal text-[#000000]">
            备注
          </View>
          <View
            className={`flex w-full items-center rounded-md border-4 border-gray-300`}
          >
            <TextArea
              className={"flex-1"}
              placeholder="请输入备注"
              rows={4}
              maxLength={200}
              showCount
              value={orderShipVO?.remark || ""}
              onChange={(value) => {
                setOrderShipVO((prev: any) => {
                  return {
                    ...prev!,
                    remark: value,
                  };
                });
              }}
            />
          </View>
        </View>
      </View>

      <View className="flex flex-col gap-2.5">
        <View className="flex items-center justify-between border-b border-b-gray-200 pb-2.5">
          <Text className="text-base font-semibold">商品信息</Text>
          <View
            className="text-primary flex cursor-pointer items-center text-sm"
            onClick={() => setShowAddGoodsPopup(true)}
          >
            <Icon name="plus" size={14} />
            <View>添加商品</View>
          </View>
        </View>

        <View>
          <Table
            columns={[
              {
                title: "商品名称",
                key: "goodsName",
                fixed: "left",
              },
              {
                title: "规格",
                key: "goodsSpec",
              },
              {
                title: "单位",
                key: "goodsUnit",
              },
              {
                title: "件数（件）",
                key: "goodsCount",
              },
              {
                title: "单重（kg）",
                key: "goodsWeight",
              },
              {
                title: "总重（kg）",
                key: "goodsTotalWeight",
              },
              {
                title: "单价（元）",
                key: "goodsPrice",
              },
              {
                title: "总价（元）",
                key: "goodsTotalPrice",
              },
              {
                title: "操作",
                key: "action",
              },
            ]}
            data={[]}
          />
        </View>

        <Popup
          duration={150}
          style={{
            minHeight: "auto",
          }}
          visible={showAddGoodsPopup}
          position="bottom"
          title="添加商品"
          onClose={() => {
            setShowAddGoodsPopup(false);
            resetGoodsForm();
          }}
          onOverlayClick={() => {
            setShowAddGoodsPopup(false);
            resetGoodsForm();
          }}
          lockScroll
        >
          <View className="flex flex-col gap-3 p-2.5">
            <View className="text-neutral-darkest text-sm font-medium">
              商品名称
            </View>
            <View className="border-neutral-base relative flex h-10 w-full items-center rounded-md border border-solid">
              <Input
                clearable
                className="placeholder:text-neutral-dark flex-1"
                placeholder="请输入商品名称"
                value={goodsFormData.productName}
                onChange={(value) =>
                  handleGoodsFormChange("productName", value)
                }
              />
              {goodsFormData.productName && (
                <Icon
                  name="circle-xmark"
                  className="mr-2 cursor-pointer"
                  size={20}
                  onClick={() => handleGoodsFormChange("productName", "")}
                />
              )}
            </View>

            <View className="text-neutral-darkest text-sm font-medium">
              产地
            </View>
            <View className="border-neutral-base relative flex h-10 w-full items-center rounded-md border border-solid">
              <Input
                clearable
                className="placeholder:text-neutral-dark flex-1"
                placeholder="请输入商品产地"
                value={goodsFormData.origin}
                onChange={(value) => handleGoodsFormChange("origin", value)}
              />
              {goodsFormData.origin && (
                <Icon
                  name="circle-xmark"
                  className="mr-2 cursor-pointer"
                  size={20}
                  onClick={() => handleGoodsFormChange("origin", "")}
                />
              )}
            </View>

            <View className="text-neutral-darkest text-sm font-medium">
              规格
            </View>
            <View className="flex flex-row gap-4">
              {[
                { label: "1粒", value: "1粒" },
                { label: "2粒", value: "2粒" },
                { label: "4粒", value: "4粒" },
              ].map((option) => (
                <View
                  key={option.value}
                  className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                    goodsFormData.spec === option.value
                      ? "bg-blue-100 text-blue-600"
                      : "border border-gray-300"
                  }`}
                  onClick={() => handleGoodsFormChange("spec", option.value)}
                >
                  {option.label}
                </View>
              ))}
            </View>

            <View className="text-neutral-darkest text-sm font-medium">
              单位
            </View>
            <View className="flex flex-row gap-4">
              {[
                { label: "kg", value: "kg" },
                { label: "个", value: "个" },
              ].map((option) => (
                <View
                  key={option.value}
                  className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                    goodsFormData.unit === option.value
                      ? "bg-blue-100 text-blue-600"
                      : "border border-gray-300"
                  }`}
                  onClick={() => handleGoodsFormChange("unit", option.value)}
                >
                  {option.label}
                </View>
              ))}
            </View>

            <View className="text-neutral-darkest text-sm font-medium">
              数量(件)
            </View>
            <View className="border-neutral-base relative flex h-10 w-full items-center rounded-md border border-solid">
              <Input
                clearable
                className="placeholder:text-neutral-dark flex-1"
                type="number"
                placeholder="请输入数量"
                value={goodsFormData.quantity}
                onChange={(value) => handleGoodsFormChange("quantity", value)}
              />
              {goodsFormData.quantity && (
                <Icon
                  name="circle-xmark"
                  className="mr-2 cursor-pointer"
                  size={20}
                  onClick={() => handleGoodsFormChange("quantity", "")}
                />
              )}
            </View>

            <View className="text-neutral-darkest text-sm font-medium">
              总重(KG)
            </View>
            <View className="border-neutral-base relative flex h-10 w-full items-center rounded-md border border-solid">
              <Input
                clearable
                className="placeholder:text-neutral-dark flex-1"
                type="number"
                placeholder="请输入总重量"
                value={goodsFormData.weight}
                onChange={(value) => handleGoodsFormChange("weight", value)}
              />
              {goodsFormData.weight && (
                <Icon
                  name="circle-xmark"
                  className="mr-2 cursor-pointer"
                  size={20}
                  onClick={() => handleGoodsFormChange("weight", "")}
                />
              )}
            </View>

            <View className="text-neutral-darkest text-sm font-medium">
              单价(元/KG)
            </View>
            <View className="border-neutral-base relative flex h-10 w-full items-center rounded-md border border-solid">
              <Input
                clearable
                className="placeholder:text-neutral-dark flex-1"
                type="number"
                placeholder="请输入单价"
                value={goodsFormData.price}
                onChange={(value) => handleGoodsFormChange("price", value)}
              />
              {goodsFormData.price && (
                <Icon
                  name="circle-xmark"
                  className="mr-2 cursor-pointer"
                  size={20}
                  onClick={() => handleGoodsFormChange("price", "")}
                />
              )}
            </View>
          </View>

          <View className="flex w-full flex-col bg-white">
            <View className="flex flex-row gap-2 p-3">
              <View className="flex-1">
                <Button
                  size={"large"}
                  block
                  type="default"
                  onClick={() => {
                    setShowAddGoodsPopup(false);
                    resetGoodsForm();
                  }}
                >
                  取消
                </Button>
              </View>
              <View className="flex-1">
                <Button
                  size={"large"}
                  block
                  type="primary"
                  onClick={submitGoodsForm}
                >
                  保存
                </Button>
              </View>
            </View>
          </View>
        </Popup>
      </View>
    </View>
  );
});

export default Step1Form;
