import { ScrollView, Text, View } from "@tarojs/components";
import { Button, Input, Popup, SafeArea } from "@nutui/nutui-react-taro";
import dayjs from "dayjs";
import { formatCurrency } from "@/utils/format";
import { useState } from "react";

export default function BasicInfoSection(props: {
  purchaseOrderVO: BusinessAPI.PurchaseOrderVO;
  onChange?: (purchaseOrderVO: BusinessAPI.PurchaseOrderVO) => void;
  readOnly?: boolean;
}) {
  const { purchaseOrderVO, onChange, readOnly } = props;

  const { orderVehicle } = purchaseOrderVO;

  // 弹窗可见状态
  const [visiblePopup, setVisiblePopup] = useState({
    basicInfo: false, // 基础信息弹窗
  });

  // 编辑值的状态（用于弹窗中的临时编辑）
  const [editValues, setEditValues] = useState({
    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 openBasicInfoPopup = () => {
    if (readOnly) return;
    setEditValues({
      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 updatedOrder = {
        ...purchaseOrderVO,
        orderVehicle: {
          ...orderVehicle,
          ...editValues,
          deliveryTime: editValues.deliveryTime,
          price: Number(editValues.price),
          strawCurtainPrice: Number(editValues.strawCurtainPrice),
        },
      };
      onChange(updatedOrder);
    }
    setVisiblePopup((prev) => ({ ...prev, basicInfo: false }));
  };

  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
                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
                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
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入收货地"}
                type={"text"}
                value={editValues.destination}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    destination: 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
                className={"placeholder:text-neutral-dark"}
                placeholder={"请输入发货日期"}
                type={"text"}
                value={editValues.deliveryTime}
                onChange={(value) => {
                  setEditValues((prev) => ({
                    ...prev,
                    deliveryTime: 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
                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
                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
                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
                    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="rounded-lg border border-solid border-gray-200 bg-white">
        <View className="grid grid-cols-1 p-3">
          <View className="flex !h-8 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">
              {orderVehicle?.vehicleNo || "请填写"}
            </View>
          </View>
          <View className="flex !h-8 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">
              {orderVehicle?.origin || "请填写"}
            </View>
          </View>
          <View className="flex !h-8 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">
              {orderVehicle?.destination || "请填写"}
            </View>
          </View>
          <View className="flex !h-8 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">
              {orderVehicle?.deliveryTime
                ? dayjs(orderVehicle.deliveryTime).format("YYYY年MM月DD日")
                : "请填写"}
            </View>
          </View>
          <View className="flex !h-8 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">
              {orderVehicle?.plate || "请填写"}
            </View>
          </View>
          <View className="flex !h-8 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">
              {orderVehicle?.phone || "请填写"}
            </View>
          </View>
          <View className="flex !h-8 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">
              {orderVehicle?.priceType === "MAIN_FREIGHT"
                ? "主运费"
                : orderVehicle?.priceType === "SHORT_TRANSPORT"
                  ? "短驳费"
                  : "请选择"}
            </View>
          </View>
          <View className="flex !h-8 flex-row items-center justify-between">
            <View className="flex items-center">
              <View className="text-neutral-dark flex-shrink-0 text-sm">
                运费（元）
              </View>
            </View>
            <View className={"flex flex-1 items-center justify-end gap-2.5"}>
              <View className="text-neutral-darkest text-sm font-medium">
                {formatCurrency(orderVehicle?.price || 0)}
              </View>
              {purchaseOrderVO.orderDealer && (
                <View className="ml-1 rounded-full bg-blue-100 px-2 py-0.5">
                  <Text className="text-xs text-blue-600">
                    {purchaseOrderVO.orderDealer.freightCostFlag
                      ? "计入成本"
                      : "不计入成本"}
                  </Text>
                </View>
              )}
            </View>
          </View>
          <View className="flex !h-8 flex-row items-center justify-between">
            <View className="flex items-center">
              <View className="text-neutral-dark flex-shrink-0 text-sm">
                草帘费
              </View>
            </View>
            <View className={"flex flex-1 items-center justify-end gap-2.5"}>
              <View className="text-neutral-darkest text-sm font-medium">
                {orderVehicle?.openStrawCurtain ? "开启" : "关闭"}
              </View>
            </View>
          </View>
          {orderVehicle?.openStrawCurtain && (
            <View className="flex !h-8 flex-row items-center justify-between">
              <View className="flex items-center">
                <View className="text-neutral-dark flex-shrink-0 text-sm">
                  草帘费金额（元）
                </View>
              </View>
              <View className={"flex flex-1 items-center justify-end gap-2.5"}>
                <View className="text-neutral-darkest text-sm font-medium">
                  {formatCurrency(orderVehicle?.strawCurtainPrice || 0)}
                </View>
                {purchaseOrderVO.orderDealer && (
                  <View className="ml-1 rounded-full bg-blue-100 px-2 py-0.5">
                    <Text className="text-xs text-blue-600">
                      {purchaseOrderVO.orderDealer.strawMatCostFlag
                        ? "计入成本"
                        : "不计入成本"}
                    </Text>
                  </View>
                )}
              </View>
            </View>
          )}
        </View>
        {!readOnly && (
          <View className="flex justify-center border-t border-gray-200 p-2">
            <Button
              size="small"
              type="primary"
              fill="outline"
              onClick={openBasicInfoPopup}
            >
              修改基础信息
            </Button>
          </View>
        )}
      </View>
    </>
  );
}
