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

export default function RebateCalcSection(props: {
  orderVO: BusinessAPI.OrderVO;
  onChange?: (orderVO: BusinessAPI.OrderVO) => void;
  readOnly?: boolean;
  calculator: OrderCalculator;
}) {
  const { orderVO, onChange, readOnly, calculator } = props;

  const totalNetWeight = calculator.getTotalNetWeight();
  const orderRebate = orderVO.orderRebate || {};
  const [tempOrderRebate, setTempOrderRebate] =
    useState<BusinessAPI.OrderRebate>({});
  const [visible, setVisible] = useState(false);

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

  const handleRebateChange = (field: string, value: any) => {
    setTempOrderRebate((prev) => {
      const newOrderRebate = {
        ...prev,
        [field]: value,
      };

      if (field === "calcMethod") {
        if (value === "NET_WEIGHT") {
          return { ...newOrderRebate, netWeight: totalNetWeight };
        } else {
          return { ...newOrderRebate, netWeight: undefined };
        }
      } else {
        return newOrderRebate;
      }
    });
  };

  const handleSave = () => {
    // 如果是按净重计算，自动计算返点金额
    let finalOrderRebate = { ...tempOrderRebate };

    const newOrderVO = {
      ...orderVO,
      orderRebate: finalOrderRebate,
    };

    onChange?.(newOrderVO);
    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">
          {!readOnly ? (
            <View
              className="flex flex-1 flex-col"
              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 flex-1 items-end">
                <Text className="w-full border-b-2 border-red-500 pb-2 text-3xl font-bold text-red-500 focus:outline-none">
                  {calculator.calculateRebateAmount(orderRebate)}
                </Text>
              </View>
            </View>
          ) : (
            <View className="flex flex-1 flex-col">
              <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 flex-1 items-end">
                <Text className="w-full py-2 text-3xl font-bold text-red-500">
                  {calculator.calculateRebateAmount(orderRebate)}
                </Text>
              </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">
                {orderRebate.name || "未设置"}
              </Text>
            </View>
            <View className="flex items-center justify-between">
              <Text className="text-sm text-gray-500">计算方式</Text>
              <Text className="text-sm font-medium">
                {orderRebate.calcMethod === "NET_WEIGHT"
                  ? "按净重计算"
                  : orderRebate.calcMethod === "FIXED_AMOUNT"
                    ? "固定金额"
                    : "不固定"}
              </Text>
            </View>
            {orderRebate.calcMethod === "NET_WEIGHT" && (
              <>
                <View className="flex items-center justify-between">
                  <Text className="text-sm text-gray-500">净重</Text>
                  <Text className="text-sm font-medium">
                    {orderRebate.netWeight || 0} 斤
                  </Text>
                </View>
                <View className="flex items-center justify-between">
                  <Text className="text-sm text-gray-500">单价</Text>
                  <Text className="text-sm font-medium">
                    {orderRebate.unitPrice || 0} 元/斤
                  </Text>
                </View>
              </>
            )}
          </View>
        </View>
      </View>

      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        closeable
        destroyOnClose
        visible={visible}
        title="返点信息"
        position="bottom"
        round
        onClose={() => setVisible(false)}
      >
        <ScrollView scrollY className="max-h-150">
          <View className="flex flex-col gap-3 p-2.5">
            {/* 返点计算方式选择 */}
            <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 ${
                  tempOrderRebate.calcMethod === "NET_WEIGHT"
                    ? "bg-blue-100 text-blue-600"
                    : "border border-gray-300"
                }`}
                onClick={() => {
                  handleRebateChange("calcMethod", "NET_WEIGHT");
                }}
              >
                按净重计算
              </View>
              <View
                className={`flex flex-1 flex-row items-center justify-center rounded-md py-2 ${
                  tempOrderRebate.calcMethod === "FIXED_AMOUNT"
                    ? "bg-blue-100 text-blue-600"
                    : "border border-gray-300"
                }`}
                onClick={() => {
                  handleRebateChange("calcMethod", "FIXED_AMOUNT");
                }}
              >
                固定金额
              </View>
            </View>

            {/* 按净重计算时的字段 */}
            {tempOrderRebate.calcMethod === "NET_WEIGHT" && (
              <>
                <View className="flex items-center justify-between rounded-md bg-gray-100 p-3">
                  <View className="text-neutral-darkest text-sm font-medium">
                    净重（斤）
                  </View>
                  <View className="text-neutral-darkest text-sm font-medium">
                    {tempOrderRebate.netWeight?.toString() || ""} 斤
                  </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 flex-1"
                    placeholder="请输入单价"
                    type="digit"
                    value={tempOrderRebate.unitPrice?.toString() || ""}
                    onChange={(value) => {
                      const numValue = validatePrice(value);
                      if (numValue !== undefined) {
                        handleRebateChange("unitPrice", numValue);
                      }
                    }}
                  />
                  <View className="mr-2">元/斤</View>
                </View>

                <View className="flex items-center justify-between rounded-md bg-gray-100 p-3">
                  <View className="text-neutral-darkest text-sm font-medium">
                    返点金额
                  </View>
                  <View className="text-neutral-darkest text-sm font-medium">
                    {calculator.calculateRebateAmount(tempOrderRebate)}元
                  </View>
                </View>
              </>
            )}
            {tempOrderRebate.calcMethod === "FIXED_AMOUNT" && (
              <>
                <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 flex-1"
                    placeholder="请输入返点金额"
                    type="digit"
                    value={tempOrderRebate.amount?.toString() || ""}
                    onChange={(value) => {
                      const numValue = validatePrice(value);
                      if (numValue !== undefined) {
                        handleRebateChange("amount", numValue);
                      }
                    }}
                  />
                  <View className="mr-2">元</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={handleSave}
                >
                  保存
                </Button>
              </View>
            </View>
          </View>
        </ScrollView>
        <SafeArea position="bottom" />
      </Popup>
    </View>
  );
}
