import { ScrollView, Text, View } from "@tarojs/components";
import {
  Button,
  DatePicker,
  Input,
  PickerOption,
  Popup,
  Radio,
  SafeArea,
} from "@nutui/nutui-react-taro";
import dayjs from "dayjs";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import businessServices from "@/services/business";
import { Icon } from "@/components";
import { generateShortId } from "@/utils";

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

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

  const { orderVehicle } = orderVO;

  // 暴露 validateForm 方法
  useImperativeHandle(ref, () => ({
    validateForm: () => {
      // 校验本车次号
      if (!orderVehicle?.vehicleNo) {
        return "请输入本车次号";
      }

      // 校验运费类型
      if (!orderVehicle?.priceType) {
        return "请选择运费类型";
      }

      return null;
    },
  }));

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

  // 主运费
  const mainCost = costList.find(
    (cost) => cost.type === "LOGISTICS_TYPE" && cost.name === "主运费",
  );

  // 短驳费
  const shortCost = costList.find(
    (cost) => cost.type === "LOGISTICS_TYPE" && cost.name === "短驳费",
  );

  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 [visiblePopup, setVisiblePopup] = useState({
    basicInfo: false, // 基础信息弹窗
  });

  // 编辑值的状态（用于弹窗中的临时编辑）
  const [editValues, setEditValues] = useState({
    driver: orderVehicle?.driver || "",
    dealerName: orderVehicle?.dealerName || "",
    vehicleNo: orderVehicle?.vehicleNo || "",
    origin: orderVehicle?.origin || "",
    destination: orderVehicle?.destination || "",
    deliveryTime: orderVehicle?.deliveryTime || "",
    plate: orderVehicle?.plate || "",
    phone: orderVehicle?.phone || "",
    priceType: orderVehicle?.priceType || "MAIN_FREIGHT",
    price: orderVehicle?.price || 0,
    openStrawCurtain: orderVehicle?.openStrawCurtain || false,
    strawCurtainPrice: orderVehicle?.strawCurtainPrice || 0,
  });

  // 上一车次号
  const [lastVehicleNo, setLastVehicleNo] = useState<string | null>(null);
  // 是否正在获取上一车次号
  const [loadingLastVehicleNo, setLoadingLastVehicleNo] = useState(false);

  // 获取上一车次号
  const fetchLastVehicleNo = async (
    dealerId: BusinessAPI.DealerVO["dealerId"],
    // 强制重新获取
    force: boolean = false,
  ) => {
    if (!force) {
      // 如果已经有车次号，则不需要获取上一车次号
      if (orderVehicle?.vehicleNo || !dealerId) {
        return;
      }

      // 避免重复请求
      if (loadingLastVehicleNo || lastVehicleNo) {
        return;
      }
    } else {
      if (loadingLastVehicleNo || !dealerId) {
        return;
      }
    }

    setLoadingLastVehicleNo(true);
    try {
      const { data: res } = await businessServices.order.getLastVehicleNo({
        lastVehicleNoQry: {
          dealerId: orderVO.orderDealer.dealerId,
        },
      });

      if (res.success && res.data) {
        setLastVehicleNo(res.data);

        // 解析车次号中的数字部分并加1
        const numberPart = res.data.match(/(\d+)$/);
        if (numberPart) {
          const nextNumber = parseInt(numberPart[1]) + 1;
          const nextVehicleNo = res.data.replace(
            /(\d+)$/,
            nextNumber.toString(),
          );

          // 更新车次号
          updateVehicleNo(nextVehicleNo);
        }
      }
    } catch (error) {
      console.error("获取上一车次号失败:", error);
    } finally {
      setLoadingLastVehicleNo(false);
    }
  };

  // 组件加载时获取上一车次号
  useEffect(() => {
    fetchLastVehicleNo(orderVO.orderDealer.dealerId, true);
  }, [orderVO.orderDealer.dealerId]);

  // 打开基础信息弹窗
  const openBasicInfoPopup = () => {
    if (readOnly) return;
    setEditValues({
      driver: orderVehicle?.driver || "",
      dealerName: orderVehicle?.dealerName || "",
      vehicleNo: orderVehicle?.vehicleNo || "",
      origin: orderVehicle?.origin || "",
      destination: orderVehicle?.destination || "",
      deliveryTime: orderVehicle?.deliveryTime || "",
      plate: orderVehicle?.plate || "",
      phone: orderVehicle?.phone || "",
      priceType: orderVehicle?.priceType || "MAIN_FREIGHT",
      price: orderVehicle?.price || 0,
      openStrawCurtain: orderVehicle?.openStrawCurtain || false,
      strawCurtainPrice: orderVehicle?.strawCurtainPrice || 0,
    });
    setVisiblePopup((prev) => ({ ...prev, basicInfo: true }));
  };

  // 保存基础信息
  const saveBasicInfo = () => {
    if (onChange) {
      const newOrderCostList = orderVO.orderCostList.filter((cost) => {
        return cost.type !== "LOGISTICS_TYPE";
      });

      const orderVehicle = editValues;
      const costName =
        orderVehicle.priceType === "SHORT_TRANSPORT" ? "短驳费" : "主运费";
      const cost2 = costList?.find(
        (cost) => cost.name === costName && cost.type === "LOGISTICS_TYPE",
      );

      // 加运费
      if (orderVehicle.price && cost2) {
        newOrderCostList.push({
          orderCostId: generateShortId(),
          costId: cost2.costId || "",
          name: cost2.name || "",
          price: orderVehicle.price,
          unit: cost2.unit || "元",
          count: 1,
          type: "LOGISTICS_TYPE",
          costItemIds: [],
          belong: cost2.belong,
          selected: true,
        });
      }

      const cost3 = costList?.find(
        (cost) => cost.name === "草帘费" && cost.type === "LOGISTICS_TYPE",
      );
      // 加草帘
      if (orderVehicle.openStrawCurtain && cost3) {
        newOrderCostList.push({
          orderCostId: generateShortId(),
          costId: cost3.costId || "",
          name: cost3.name || "",
          price: orderVehicle.strawCurtainPrice!,
          unit: cost3.unit || "元",
          count: 1,
          type: "LOGISTICS_TYPE",
          costItemIds: [],
          belong: cost3.belong,
          selected: true,
        });
      }

      const updatedOrder = {
        ...orderVO,
        orderVehicle: {
          ...orderVehicle,
          ...editValues,
          deliveryTime: editValues.deliveryTime,
          price: Number(editValues.price),
          strawCurtainPrice: Number(editValues.strawCurtainPrice),
        },
        orderCostList: newOrderCostList.filter(
          (orderCost) => orderCost.price !== 0,
        ),
      };
      onChange(updatedOrder);
    }
    setVisiblePopup((prev) => ({ ...prev, basicInfo: false }));
  };

  // 更新车次号
  const updateVehicleNo = (value: string) => {
    if (onChange) {
      const updatedOrder = {
        ...orderVO,
        orderVehicle: {
          ...orderVehicle,
          vehicleNo: value,
        },
      };
      onChange(updatedOrder);
    }
  };

  // 更新运费类型
  const updatePriceType = (value: BusinessAPI.OrderVehicle["priceType"]) => {
    if (onChange) {
      const updatedOrder = {
        ...orderVO,
        orderVehicle: {
          ...orderVehicle,
          priceType: value,
        },
        orderCostList: orderVO.orderCostList.map((orderCost) => {
          if (orderCost.type === "LOGISTICS_TYPE") {
            if (
              orderCost.name === "短驳费" &&
              value === "MAIN_FREIGHT" &&
              mainCost
            ) {
              return {
                ...orderCost,
                costId: mainCost.costId,
                name: mainCost.name,
                belong: mainCost.belong,
                unit: mainCost.unit || orderCost.unit || "元",
              };
            }
            if (
              orderCost.name === "主运费" &&
              value === "SHORT_TRANSPORT" &&
              shortCost
            ) {
              return {
                ...orderCost,
                costId: shortCost.costId,
                name: shortCost.name,
                belong: shortCost.belong,
                unit: shortCost.unit || orderCost.unit || "元",
              };
            }
          }

          return orderCost;
        }),
      };
      onChange(updatedOrder);
    }
  };

  // 显示的参考车次号
  const displayReferenceVehicleNo = () => {
    if (lastVehicleNo) {
      return lastVehicleNo;
    }
    return "获取中...";
  };

  return (
    <>
      {/* 基础信息编辑弹窗 */}
      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        visible={visiblePopup.basicInfo}
        className={"flex flex-col"}
        position="bottom"
        title={"编辑基础信息"}
        onClose={() =>
          setVisiblePopup((prev) => ({ ...prev, basicInfo: false }))
        }
        onOverlayClick={() => {
          setVisiblePopup((prev) => ({ ...prev, basicInfo: false }));
        }}
        lockScroll
      >
        <ScrollView scrollY className="h-96">
          <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 flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入本车次号"}
                type={"text"}
                value={editValues.vehicleNo}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    vehicleNo: value,
                  }));
                }}
              />
            </View>

            <View className={"text-neutral-darkest text-sm font-medium"}>
              发货地
            </View>
            <View
              className={
                "border-neutral-base flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入发货地"}
                type={"text"}
                value={editValues.origin}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    origin: value,
                  }));
                }}
              />
            </View>

            <View className={"text-neutral-darkest text-sm font-medium"}>
              收货地
            </View>
            <View
              className={
                "border-neutral-base flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入收货地"}
                type={"text"}
                value={editValues.destination}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    destination: value,
                  }));
                }}
              />
            </View>

            <View>
              <View className="mb-1 block text-sm font-normal text-[#000000]">
                发货日期
              </View>
              <View
                className={
                  "border-neutral-base flex flex-row items-center rounded-md border border-solid"
                }
              >
                <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"}>
                    {editValues.deliveryTime || "请输入发货日期"}
                  </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) => {
                    setEditValues((prev) => ({
                      ...prev,
                      deliveryTime: dayjs(values.join("-")).format(
                        "YYYY-MM-DD",
                      ),
                    }));
                  }}
                />
              </View>
            </View>

            <View className={"text-neutral-darkest text-sm font-medium"}>
              车牌号
            </View>
            <View
              className={
                "border-neutral-base flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入车牌号"}
                type={"text"}
                value={editValues.plate}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    plate: value,
                  }));
                }}
              />
            </View>

            <View className={"text-neutral-darkest text-sm font-medium"}>
              联系电话
            </View>
            <View
              className={
                "border-neutral-base flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入联系电话"}
                type={"text"}
                value={editValues.phone}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    phone: value,
                  }));
                }}
              />
            </View>

            <View className={"text-neutral-darkest text-sm font-medium"}>
              运费类型
            </View>
            <View className="flex flex-row gap-4">
              <View
                className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                  editValues.priceType === "MAIN_FREIGHT"
                    ? "bg-blue-100 text-blue-600"
                    : "border border-gray-300"
                }`}
                onClick={() => {
                  setEditValues((prev) => ({
                    ...prev,
                    priceType: "MAIN_FREIGHT",
                  }));
                }}
              >
                主运费
              </View>
              <View
                className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                  editValues.priceType === "SHORT_TRANSPORT"
                    ? "bg-blue-100 text-blue-600"
                    : "border border-gray-300"
                }`}
                onClick={() => {
                  setEditValues((prev) => ({
                    ...prev,
                    priceType: "SHORT_TRANSPORT",
                  }));
                }}
              >
                短驳费
              </View>
            </View>

            <View className={"text-neutral-darkest text-sm font-medium"}>
              运费（元）
            </View>
            <View
              className={
                "border-neutral-base flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入运费"}
                type={"digit"}
                value={editValues.price.toString()}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    price: parseFloat(value) || 0,
                  }));
                }}
              />
              <View className="mr-2">元</View>
            </View>

            <View className={"text-neutral-darkest text-sm font-medium"}>
              草帘费
            </View>
            <View className="flex flex-row gap-4">
              <View
                className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                  editValues.openStrawCurtain
                    ? "bg-blue-100 text-blue-600"
                    : "border border-gray-300"
                }`}
                onClick={() => {
                  setEditValues((prev) => ({
                    ...prev,
                    openStrawCurtain: true,
                  }));
                }}
              >
                用了
              </View>
              <View
                className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                  !editValues.openStrawCurtain
                    ? "bg-blue-100 text-blue-600"
                    : "border border-gray-300"
                }`}
                onClick={() => {
                  setEditValues((prev) => ({
                    ...prev,
                    openStrawCurtain: false,
                  }));
                }}
              >
                没用
              </View>
            </View>

            {editValues.openStrawCurtain && (
              <>
                <View className={"text-neutral-darkest text-sm font-medium"}>
                  草帘费金额（元）
                </View>
                <View
                  className={
                    "border-neutral-base flex flex-row items-center rounded-md border border-solid"
                  }
                >
                  <Input
                    clearable
                    className={"placeholder:text-neutral-dark"}
                    placeholder={"请输入草帘费金额"}
                    type={"digit"}
                    value={editValues.strawCurtainPrice.toString()}
                    onChange={(value) => {
                      setEditValues((prev) => ({
                        ...prev,
                        strawCurtainPrice: parseFloat(value) || 0,
                      }));
                    }}
                  />
                  <View className="mr-2">元</View>
                </View>
              </>
            )}
          </View>
        </ScrollView>
        <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={() => {
                  setVisiblePopup((prev) => ({ ...prev, basicInfo: false }));
                }}
              >
                取消
              </Button>
            </View>
            <View className={"flex-1"}>
              <Button
                size={"large"}
                block
                type="primary"
                onClick={saveBasicInfo}
              >
                保存
              </Button>
            </View>
          </View>
          <SafeArea position={"bottom"} />
        </View>
      </Popup>

      <View className={"flex flex-col gap-2.5"}>
        {/* 本车次号 */}
        <View className="flex flex-col gap-2.5">
          <View className={"flex flex-row items-center justify-between"}>
            <View className="text-neutral-darkest flex flex-row text-sm font-bold">
              <Icon name="truck" size={16} className="mr-1" />
              本车次号
            </View>
            <View className="text-neutral-darker text-center text-xs">
              参考上一车：{displayReferenceVehicleNo()}
            </View>
          </View>
        </View>

        {readOnly ? (
          <View className="flex flex-col gap-2.5">
            <View
              className="flex flex-row items-center justify-between rounded-md p-2.5"
              style={{
                background: "linear-gradient(101deg, #F8FAFF 25%, #F0F5FF 74%)",
              }}
            >
              <View className="text-neutral-darkest text-sm font-medium">
                {orderVehicle?.vehicleNo
                  ? "第" + orderVehicle?.vehicleNo + "车"
                  : "暂未生成车次"}
              </View>
            </View>
          </View>
        ) : (
          <View className="flex flex-col gap-2.5">
            <View
              className={`flex h-10 flex-1 items-center rounded-md border-4 border-gray-300`}
            >
              <Input
                clearable
                placeholder="请输入车次号"
                type="text"
                value={orderVehicle?.vehicleNo || ""}
                onChange={(value) => updateVehicleNo(value)}
              />
            </View>
          </View>
        )}

        {/* 运费信息 */}
        <View className="flex flex-col gap-2.5">
          <View className="text-neutral-darkest flex flex-row text-sm font-bold">
            <Icon name="money-bill" size={16} className="mr-1" />
            运费信息
          </View>
          <View
            className="flex flex-row items-center justify-between rounded-md p-2.5"
            style={{
              background: "linear-gradient(101deg, #F8FAFF 25%, #F0F5FF 74%)",
            }}
          >
            <Text className="pb-2 text-3xl font-bold text-red-500">
              {orderVehicle?.price || 0}
            </Text>
            <View className="text-neutral-darkest text-sm font-medium">
              {readOnly ? (
                <View>
                  {orderVehicle?.priceType === "MAIN_FREIGHT"
                    ? "主运费"
                    : orderVehicle?.priceType === "SHORT_TRANSPORT"
                      ? "短驳费"
                      : "未选择"}
                </View>
              ) : (
                <Radio.Group
                  direction={"horizontal"}
                  value={orderVehicle?.priceType}
                  onChange={(value) =>
                    updatePriceType(
                      value as BusinessAPI.OrderVehicle["priceType"],
                    )
                  }
                >
                  <Radio value="MAIN_FREIGHT">主运费</Radio>
                  <Radio value="SHORT_TRANSPORT">短驳费</Radio>
                </Radio.Group>
              )}
            </View>
          </View>
        </View>

        {/* 草帘 */}
        <View className="flex flex-col gap-2.5">
          <View className="text-neutral-darkest flex flex-row text-sm font-bold">
            <Icon name="receipt" size={16} className="mr-1" />
            草帘
          </View>

          <View
            className="flex flex-row items-center justify-between rounded-md p-2.5"
            style={{
              background: "linear-gradient(101deg, #F8FAFF 25%, #F0F5FF 74%)",
            }}
          >
            {orderVehicle?.openStrawCurtain ? (
              <Text className="pb-2 text-3xl font-bold text-red-500">
                {orderVehicle?.strawCurtainPrice || 0}
              </Text>
            ) : (
              <View className="text-neutral-darkest text-sm font-medium">
                没用
              </View>
            )}
          </View>
        </View>

        {/* 路线和其他信息卡片 */}
        <View className="flex flex-col gap-2.5 rounded-lg bg-gray-50 p-2.5">
          <View className="flex flex-row justify-between">
            <View className="text-neutral-dark text-xs">路线</View>
            <View className="text-neutral-darkest text-xs font-medium">
              {orderVehicle?.origin || "发货地"} {"->"}{" "}
              {orderVehicle?.destination || "收货地"}
            </View>
          </View>
          <View className="flex flex-row justify-between">
            <View className="text-neutral-dark text-xs">信息</View>
            <View className="text-neutral-darkest text-xs font-medium">
              {orderVehicle?.deliveryTime
                ? dayjs(orderVehicle.deliveryTime).format("YYYY-MM-DD")
                : "发货日期"}{" "}
              | {orderVehicle?.plate || "车牌号"} |{" "}
              {orderVehicle?.phone || "联系电话"}
            </View>
          </View>
        </View>

        {!readOnly && (
          <Button
            icon={<Icon name="pen-to-square" size={18} />}
            size={"large"}
            type="primary"
            fill="outline"
            block
            onClick={openBasicInfoPopup}
          >
            修改基础信息
          </Button>
        )}
      </View>
    </>
  );
});
