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

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

  const calculator = new PurchaseOrderCalculator(purchaseOrderVO);

  const [visible, setVisible] = useState(false);

  const [taxProvision, setTaxProvision] = useState<number>(
    orderDealer?.taxProvision || 0,
  );

  useEffect(() => {
    if (!orderDealer?.taxProvision) {
      const defaultValue = calculator.getDefaultTaxProvision();
      setTaxProvision(defaultValue);
      // 更新父组件的状态
      onChange?.({
        ...purchaseOrderVO,
        orderDealer: {
          ...orderDealer,
          taxProvision: defaultValue,
        },
      });
    }
  }, []);

  // 设置计提税金默认值
  const setDefaultTaxProvision = () => {
    const defaultValue = calculator.getDefaultTaxProvision();
    setTaxProvision(defaultValue);
  };

  useEffect(() => {}, [visible]);

  // 保存计提税金
  const saveTaxProvision = () => {
    onChange?.({
      ...purchaseOrderVO,
      orderDealer: {
        ...orderDealer,
        taxProvision: taxProvision,
      },
    });

    setVisible(false);
  };

  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="mb-2">
          <Text className="text-sm font-medium">计提税金</Text>
        </View>

        <View className="flex">
          <View className="flex-1">
            {!readOnly ? (
              <View onClick={() => setVisible(true)}>
                <View className="mb-2 flex items-center justify-between">
                  <Text className="text-sm text-gray-500">计提金额</Text>
                  <Text className="text-sm text-gray-500">元</Text>
                </View>
                <View className="relative flex">
                  <Text className="w-full border-b-2 border-red-500 pb-2 text-3xl font-bold text-red-500 focus:outline-none">
                    {taxProvision || "0.00"}
                  </Text>
                </View>
              </View>
            ) : (
              <View>
                <View className="mb-2 flex items-center justify-between">
                  <Text className="text-sm text-gray-500">计提金额</Text>
                  <Text className="text-sm text-gray-500">元</Text>
                </View>
                <View className="relative">
                  <Text className="w-full py-2 text-3xl font-bold text-red-500">
                    {taxProvision || "0.00"}
                  </Text>
                </View>
              </View>
            )}
          </View>

          <View className="flex flex-1 flex-col gap-2 pl-4">
            <View className="flex items-center justify-between">
              <Text className="text-sm text-gray-500">计提税率</Text>
              <Text className="text-sm font-medium">
                {orderDealer.accrualTaxRatio
                  ? orderDealer.accrualTaxRatio + "%"
                  : "未设置"}
              </Text>
            </View>
          </View>
        </View>
      </View>

      {/* 计提税金弹窗 */}
      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        visible={visible}
        className={"flex flex-col"}
        position="bottom"
        title={"编辑计提税金"}
        onClose={() => setVisible(false)}
        onOverlayClick={() => {
          setVisible(false);
        }}
        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 flex flex-row items-center rounded-md border border-solid"
            }
          >
            <Input
              className={"placeholder:text-neutral-dark"}
              placeholder={"请输入计提税金金额"}
              type={"digit"}
              value={taxProvision?.toString()}
              onChange={(value) => {
                const numValue = validatePrice(value);
                if (numValue !== undefined) {
                  setTaxProvision(numValue as number);
                }
              }}
            />
            <View className={"mr-2"}>元</View>
          </View>
          <View className={"flex flex-row gap-2 pt-2"}>
            <Button size="small" onClick={setDefaultTaxProvision}>
              按公式填入默认值
            </Button>
            <View className="ml-2 self-center text-xs text-gray-500">
              默认值: (市场报价 - 税费补贴) ×{" "}
              {orderDealer.accrualTaxRatio || "未设置"}%
            </View>
          </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={() => {
                  setVisible(false);
                }}
              >
                取消
              </Button>
            </View>
            <View className={"flex-1"}>
              <Button
                size={"large"}
                block
                type="primary"
                onClick={saveTaxProvision}
              >
                保存
              </Button>
            </View>
          </View>
          <SafeArea position={"bottom"} />
        </View>
      </Popup>
    </View>
  );
}
