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

interface AddCostComponentProps {
  visible: boolean;
  // 添加编辑模式的支持
  editMode?: boolean;
  orderCost?: BusinessAPI.OrderCost;
  orderCostItemList?: BusinessAPI.OrderCostItem[];
  onClose: () => void;
  onSave: (
    orderCost: BusinessAPI.OrderCost,
    orderCostItemList: BusinessAPI.OrderCostItem[],
  ) => void;
  costList: BusinessAPI.CostVO[];
  type: BusinessAPI.CostVO["type"];
}

export default function CostCreate(props: AddCostComponentProps) {
  const {
    visible,
    editMode = false,
    orderCost,
    orderCostItemList,
    onClose,
    onSave,
    costList,
    type,
  } = props;

  const costItemIds = orderCostItemList?.map((item) => item.costItemId);

  // 新增人工费表单数据
  const [selectedCost, setSelectedCost] = useState<BusinessAPI.CostVO | null>(
    null,
  );
  const [costItemCounts, setCostItemCounts] = useState<Map<string, number>>(
    new Map(),
  );

  const [amount, setAmount] = useState<number>();

  // 获取费用列表
  useEffect(() => {
    if (visible) {
      // 如果是编辑模式并且有初始数据，在获取费用列表后设置初始状态
      if (editMode && orderCost) {
        // 查找对应的费用类型
        const cost = costList?.find((c) => c.costId === orderCost.costId);
        if (cost) {
          setSelectedCost(cost);
          setAmount(orderCost.price);
          // 初始化费用项目数量
          const initialCounts = new Map<string, number>();
          cost.costItemVOList?.forEach((item) => {
            // 如果是编辑模式且匹配当前编辑的费用项，保留原有数量
            if (
              editMode &&
              orderCost &&
              costItemIds?.includes(item.costItemId)
            ) {
              const orderCostItem = orderCostItemList?.find(
                (item1) => item1.costItemId === item.costItemId,
              );
              initialCounts.set(item.costItemId, orderCostItem?.count || 0);
            } else {
              initialCounts.set(item.costItemId, 0);
            }
          });
          console.log("initialCounts", initialCounts);
          setCostItemCounts(initialCounts);
        }
      }
    }
  }, [visible, editMode, orderCost]);

  // 处理费用选择
  const handleCostSelect = (cost: BusinessAPI.CostVO) => {
    setSelectedCost(cost);
    // 初始化所有费用项目的数量为0
    const initialCounts = new Map<string, number>();
    // 使用cost.costItemVOList而不是外部传入的costItemVOList
    cost.costItemVOList?.forEach((item) => {
      // 如果是编辑模式且匹配当前编辑的费用项，保留原有数量
      if (costItemIds?.includes(item.costItemId)) {
        const orderCostItem = orderCostItemList?.find(
          (item1) => item1.costItemId === item.costItemId,
        );
        initialCounts.set(item.costItemId, orderCostItem?.count || 0);
      } else {
        initialCounts.set(item.costItemId, 0);
      }
    });
    setCostItemCounts(initialCounts);
  };

  // 处理费用项目数量变化
  const handleCostItemCountChange = (costItemId: string, count: number) => {
    setCostItemCounts((prev) => {
      const newCounts = new Map(prev);
      newCounts.set(costItemId, Math.max(0, count));
      return newCounts;
    });
  };

  // 添加费用
  const addCostItems = () => {
    if (!selectedCost) {
      return;
    }

    console.log("costItemCounts", costItemCounts);

    // 过滤掉数量为0的项目
    const selectedItems = Array.from(costItemCounts.entries())
      .filter(([_, count]) => count > 0)
      .map(([costItemId, count]) => {
        // 使用selectedCost.costItemVOList而不是外部传入的costItemVOList
        const costItem = selectedCost.costItemVOList?.find(
          (item) => item.costItemId === costItemId,
        );
        return {
          costItemId,
          count,
          costItem,
        };
      });

    // 创建OrderCost对象
    const newOrderCost: BusinessAPI.OrderCost = {
      // 如果是编辑模式，保留原有的orderCostId
      orderCostId:
        editMode && orderCost ? orderCost.orderCostId : generateShortId(),
      costId: selectedCost.costId || "",
      orderId: orderCost?.orderId || "",
      name: selectedCost.name || "",
      price: amount || 0,
      unit: selectedCost.unit || "元",
      count: 1, // 总数为1，因为我们将所有费用项目合并到一个OrderCost中
      costItemIds: selectedItems.map((item) => item.costItemId) || [],
      type: type,
      belong: selectedCost.belong,
      selected: true,
    };

    console.log("selectedItems", selectedItems);
    // 创建OrderCostItem数组
    const newOrderCostItems: BusinessAPI.OrderCostItem[] = selectedItems.map(
      ({ costItemId, count, costItem }) => {
        const orderCostItem = orderCostItemList?.find(
          (orderCostItem) => orderCostItem.costItemId === costItem?.costItemId,
        );
        if (orderCostItem) {
          return {
            ...orderCostItem,
            count: count,
          };
        }
        return {
          ...costItem,
          orderCostItemId: generateShortId(),
          costItemId: costItemId,
          orderId: orderCost?.orderId || "",
          count: count,
          selected: true,
          rule: costItem?.rule!,
        };
      },
    );
    console.log("newOrderCostItems", newOrderCostItems);

    // 调用onSave，传递OrderCost和OrderCostItem数组
    onSave(newOrderCost, newOrderCostItems);

    // 重置选择并关闭弹窗
    setSelectedCost(null);
    setCostItemCounts(new Map());
    onClose();
  };

  // 渲染费用选择
  const renderCostSelection = () => {
    // 编辑模式下不允许更改费用类型
    if (editMode) {
      return (
        <View className="mb-4">
          <View className="mb-2 text-sm text-gray-600">费用类型</View>
          <View className="rounded-lg bg-gray-100 p-3">
            <View className="text-base font-medium text-gray-800">
              {selectedCost?.name || "未知费用类型"}
            </View>
          </View>
          {/* 显示金额输入框 */}
          <View className="mt-4">
            <View className="mb-2 text-sm text-gray-600">费用金额</View>
            <View
              className={
                "border-neutral-base flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                type={"digit"}
                value={amount?.toString()}
                placeholder="请输入费用金额"
                onChange={(value) => {
                  const num = Number(value);
                  if (!Number.isNaN(num) && num >= 0) {
                    setAmount(num);
                  }
                }}
              />
            </View>
          </View>
        </View>
      );
    }

    return (
      <View className="mb-4">
        <View className="mb-2 text-sm text-gray-600">选择费用类型</View>
        <ScrollView className="mb-2.5" scrollX>
          <View className="flex w-fit flex-row gap-2.5">
            {costList
              .filter((cost) => {
                return !(cost.name === "空箱费" || cost.name === "纸箱费");
              })
              ?.map((cost) => (
                <View
                  key={cost.costId}
                  className={"flex flex-col items-center justify-center"}
                  onClick={() => handleCostSelect(cost)}
                >
                  <View
                    className={classNames(
                      "border-primary box-content !size-16 overflow-hidden rounded-xl border-4 object-cover",
                      {
                        "border-primary": selectedCost?.costId === cost.costId,
                        "border-transparent":
                          selectedCost?.costId !== cost.costId,
                      },
                    )}
                  >
                    {/*@ts-ignore*/}
                    {cost.image ? (
                      <Image
                        //@ts-ignore
                        src={cost.image}
                        className="h-full w-full"
                        mode={"aspectFill"}
                        alt={cost.name}
                      />
                    ) : (
                      <View className="text-neutral-darker flex h-full w-full items-center justify-center bg-gray-100 text-xs">
                        {cost.name.substring(0, 2)}
                      </View>
                    )}
                  </View>
                  <View className="text-center text-xs">{cost.name}</View>
                </View>
              ))}
          </View>
        </ScrollView>
        {/* 显示金额输入框 */}
        {selectedCost && (
          <View className="mt-4">
            <View className="mb-2 text-sm text-gray-600">费用金额</View>
            <View
              className={
                "border-neutral-base flex flex-row items-center rounded-md border border-solid"
              }
            >
              <Input
                clearable
                className={"placeholder:text-neutral-dark"}
                type={"digit"}
                value={amount?.toString()}
                placeholder="请输入费用金额"
                onChange={(value) => {
                  const num = Number(value);
                  if (!Number.isNaN(num) && num >= 0) {
                    setAmount(num);
                  }
                }}
              />
            </View>
          </View>
        )}
      </View>
    );
  };

  // 渲染费用项目选择
  const renderCostItemSelection = () => {
    if (!selectedCost) return null;

    // 使用selectedCost.costItemVOList而不是外部传入的costItemVOList
    const relevantCostItems = selectedCost.costItemVOList || [];

    if (relevantCostItems.length === 0) return null;

    return (
      <View className="mb-4">
        <View className="mb-2 text-sm text-gray-600">
          费用项目（点击 +/- 修改数量，0表示不使用）
        </View>
        <View className="space-y-3">
          {relevantCostItems.map((costItem) => {
            const currentCount = costItemCounts.get(costItem.costItemId) || 0;

            console.log("currentCount: ", currentCount);
            return (
              <View
                key={costItem.costItemId}
                className="flex items-center justify-between rounded-lg bg-gray-50 p-3"
              >
                <View className="text-gray-800">{costItem.name}</View>
                <View className="flex items-center">
                  <View
                    className="flex h-8 w-8 items-center justify-center rounded-l bg-gray-200"
                    onClick={() => {
                      handleCostItemCountChange(
                        costItem.costItemId,
                        Math.max(0, currentCount - 1),
                      );
                    }}
                  >
                    <Icon name="minus" size={16} />
                  </View>
                  <View className="flex h-8 w-12 items-center justify-center border-y border-gray-200">
                    <Input
                      clearable
                      type="digit"
                      value={currentCount.toString()}
                      align={"center"}
                      className="!h-8 !w-12 !p-0 !text-center"
                      onChange={(value) => {
                        const num = Number(value);
                        if (!Number.isNaN(num) && num >= 0) {
                          handleCostItemCountChange(costItem.costItemId, num);
                        }
                      }}
                    />
                  </View>
                  <View
                    className="flex h-8 w-8 items-center justify-center rounded-r bg-gray-200"
                    onClick={() => {
                      handleCostItemCountChange(
                        costItem.costItemId,
                        currentCount + 1,
                      );
                    }}
                  >
                    <Icon name="plus" size={16} />
                  </View>
                  <View className="ml-2 text-gray-800">
                    {costItem.unit || "个"}
                  </View>
                </View>
              </View>
            );
          })}
        </View>
      </View>
    );
  };

  const getTitle = (type: string) => {
    if (type === "ARTIFICIAL_TYPE") {
      return "新增人工类型费用";
    }
    if (type === "MATERIAL_TYPE") {
      return "新增辅料类型费用";
    }
    if (type === "PRODUCTION_TYPE") {
      return "新增产地类型费用";
    }
    if (type === "OTHER_TYPE") {
      return "新增其他类型费用";
    }

    return "新增费用";
  };

  return (
    <Popup
      duration={150}
      style={{
        minHeight: "auto",
      }}
      visible={visible}
      position="bottom"
      title={editMode ? `编辑${orderCost?.name || "费用"}` : getTitle(type)}
      onClose={onClose}
      onOverlayClick={onClose}
      lockScroll
    >
      <ScrollView scrollY className="max-h-150">
        <View className="flex flex-col gap-3 p-2.5">
          {renderCostSelection()}

          {!selectedCost && !editMode && (
            <View className="mb-4 rounded-lg bg-yellow-50 p-4 text-center">
              <View className="text-yellow-800">请先选择一个费用类型</View>
            </View>
          )}

          {renderCostItemSelection()}
        </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={() => {
                  onClose();

                  // 重置表单
                  setSelectedCost(null);
                  setCostItemCounts(new Map());
                }}
              >
                取消
              </Button>
            </View>
            <View className="flex-1">
              <Button
                size={"large"}
                block
                type="primary"
                disabled={
                  selectedCost?.type !== "OTHER_TYPE" &&
                  (!selectedCost ||
                    Array.from(costItemCounts.values()).every(
                      (count) => count === 0,
                    ))
                }
                onClick={addCostItems}
              >
                {editMode ? "保存" : "添加"}
              </Button>
            </View>
          </View>
        </View>
        <SafeArea position="bottom" />
      </ScrollView>
    </Popup>
  );
}
