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

interface IExpenseCostCreateProps {
  onFinish?: (expressCost: BusinessAPI.ExpenseCost) => void;
  visible: boolean;
  onClose: () => void;
  editMode?: boolean;
  cost?: BusinessAPI.CostVO;
  expenseCost?: BusinessAPI.ExpenseCost;
}

export default function ExpenseCostCreate(props: IExpenseCostCreateProps) {
  const {
    onFinish,
    visible,
    onClose,
    editMode = false,
    cost: costVO,
    expenseCost: initialExpenseCost,
  } = props;

  const [expressCost, setExpressCost] = useState<BusinessAPI.ExpenseCost>();

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

  // 初始化表单数据
  useEffect(() => {
    if (visible) {
      if (editMode && initialExpenseCost) {
        // 编辑模式：回填数据
        setExpressCost(initialExpenseCost);
      } else if (costVO) {
        // 如果传入了费用类型，预填充费用类型信息
        setExpressCost({
          costId: costVO.costId,
          costName: costVO.name,
          // @ts-ignore
          expenseAmount: undefined,
          remark: "",
        });
      } else {
        // 新增模式：清空数据
        setExpressCost(undefined);
      }
      // 清空错误状态
      setFormErrors({});
    }
  }, [visible, editMode, initialExpenseCost, costVO]);

  const validateForm = () => {
    const errors = {
      costId: !expressCost?.costId,
      expenseAmount:
        !expressCost?.expenseAmount || expressCost.expenseAmount <= 0,
    };

    setFormErrors(errors);

    // 检查是否有错误
    return !Object.values(errors).some((error) => error);
  };

  const saveExpenseCost = async () => {
    if (!validateForm()) {
      return;
    }

    if (expressCost) {
      // 编辑模式下保留原有ID，新增模式下生成新ID
      const finalExpenseCost: BusinessAPI.ExpenseCost = {
        ...expressCost,
        expenseCostId: editMode
          ? initialExpenseCost?.expenseCostId || expressCost.expenseCostId
          : expressCost.expenseCostId || generateShortId(),
      };

      onFinish?.(finalExpenseCost);
    }

    // 重置表单
    setExpressCost(undefined);
    setFormErrors({});
    onClose();
  };

  return (
    <>
      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        visible={visible}
        className={"flex flex-col"}
        position="bottom"
        title={editMode ? "编辑费用" : "添加费用"}
        onClose={() => {
          onClose();
        }}
        onOverlayClick={() => {
          onClose();
        }}
        lockScroll
      >
        <ScrollView scrollY className="h-96">
          <View className={"flex flex-col gap-3 p-2.5"}>
            {/* 编辑模式或指定费用类型时，费用类型不可修改 */}
            {editMode || costVO ? (
              <>
                <View className="block text-sm font-normal text-[#000000]">
                  费用类型
                </View>
                <View className="rounded-md bg-gray-100 p-3">
                  <View className="text-base font-medium text-gray-800">
                    {expressCost?.costName || "未知费用类型"}
                  </View>
                </View>
              </>
            ) : (
              <>
                <View className="block text-sm font-normal text-[#000000]">
                  费用类型 <Text className="text-red-500">*</Text>
                </View>
                <View
                  id={"target2"}
                  className={`border-neutral-base flex flex-row items-center rounded-md ${formErrors.costId ? "border-4 border-red-500" : "border-4 border-gray-300"}`}
                >
                  <CostPicker
                    params={{
                      type: "EXPENSE_TYPE",
                    }}
                    onFinish={(costVO) => {
                      setExpressCost((prev) => {
                        return {
                          ...prev!,
                          costId: costVO.costId,
                          costName: costVO.name,
                        };
                      });

                      setFormErrors((prev) => ({
                        ...prev,
                        costId: false,
                      }));
                    }}
                    trigger={
                      <View
                        className={
                          "flex flex-1 flex-row items-center justify-between px-5"
                        }
                      >
                        <View className={"text-sm"}>
                          {expressCost?.costName || "选择费用类型"}
                        </View>
                        <Icon name={"chevron-down"} />
                      </View>
                    }
                  />
                </View>
                {formErrors.costId && (
                  <View className="mt-1 text-xs text-red-500">
                    请选择费用类型
                  </View>
                )}
              </>
            )}

            <View className={"text-neutral-darkest text-sm font-medium"}>
              金额 <Text className="text-red-500">*</Text>
            </View>
            <View
              className={`border-neutral-base flex flex-row items-center rounded-md ${formErrors.expenseAmount ? "border-4 border-red-500" : "border-4 border-gray-300"}`}
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                type={"digit"}
                value={expressCost?.expenseAmount?.toString() || ""}
                placeholder="请输入费用金额"
                onChange={(value) => {
                  const num = Number(value);
                  if (!Number.isNaN(num) && num >= 0) {
                    setExpressCost((prev) => {
                      return {
                        ...prev!,
                        expenseAmount: num,
                      };
                    });

                    // 实时清除金额错误状态
                    if (num > 0) {
                      setFormErrors((prev) => ({
                        ...prev,
                        expenseAmount: false,
                      }));
                    }
                  }
                }}
              />
            </View>
            {formErrors.expenseAmount && (
              <View className="mt-1 text-xs text-red-500">
                请输入正确的金额
              </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"
              }
            >
              <TextArea
                className={"flex-1"}
                placeholder="请输入备注信息"
                rows={4}
                maxLength={200}
                showCount
                value={expressCost?.remark || ""}
                onChange={(value) => {
                  // 备注是可选的，不需要处理错误状态
                  setExpressCost((prev: any) => {
                    return {
                      ...prev!,
                      remark: value,
                    };
                  });
                }}
              />
            </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={() => {
                  onClose();
                }}
              >
                取消
              </Button>
            </View>
            <View className={"flex-1"}>
              <Button
                size={"large"}
                block
                type="primary"
                disabled={
                  !expressCost?.costId ||
                  !expressCost?.expenseAmount ||
                  expressCost.expenseAmount <= 0 ||
                  Object.values(formErrors).some((item) => item)
                }
                onClick={saveExpenseCost}
              >
                {editMode ? "保存" : "添加"}
              </Button>
            </View>
          </View>
          <SafeArea position={"bottom"} />
        </View>
      </Popup>
    </>
  );
}
