import { View } from "@tarojs/components";
import { ExpenseProvisionCreate, Icon } from "@/components";
import { Button } from "@nutui/nutui-react-taro";
import { useState } from "react";
import ExpenseProvisionCard from "./ExpenseProvisionCard";

interface IExpenseCostProps {
  expenseRecord?: BusinessAPI.ExpenseRecordVO;
  onChange?: (expenseRecord: BusinessAPI.ExpenseRecordVO) => void;
}

export default function ExpenseCostList(props: IExpenseCostProps) {
  const { expenseRecord, onChange } = props;

  // 按 dealerName 分组
  const groupByDealer = (provisions?: BusinessAPI.ExpenseProvision[]) => {
    if (!provisions || provisions.length === 0) return {};

    return provisions.reduce(
      (groups, item) => {
        const dealerName = item.dealerName || "未分组客户";
        if (!groups[dealerName]) {
          groups[dealerName] = [];
        }
        groups[dealerName].push(item);
        return groups;
      },
      {} as Record<string, BusinessAPI.ExpenseProvision[]>,
    );
  };

  // 获取分组后的数据
  const dealerGroups = expenseRecord
    ? groupByDealer(expenseRecord.expenseProvisionList)
    : {};

  // 计算每个客户的总计
  const getDealerTotal = (vehicles: BusinessAPI.ExpenseProvision[]) => {
    return vehicles.reduce((sum, item) => sum + item.provisionAmount, 0);
  };

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

  // 管理每个客户分组的展开状态
  const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>(
    {},
  );

  // 切换分组展开状态
  const toggleGroup = (dealerName: string) => {
    setExpandedGroups((prev) => ({
      ...prev,
      [dealerName]: !prev[dealerName],
    }));
  };

  return (
    <View className="overflow-hidden rounded-md bg-white shadow-md">
      <View className="border-b border-gray-100 p-2.5">
        <View className="text-neutral-darkest text-base font-medium">
          计提汇总
        </View>
      </View>

      {expenseRecord?.expenseProvisionList?.length === 0 && (
        <View className="py-2 text-center text-sm text-gray-500">
          暂无计提数据
        </View>
      )}
      {Object.entries(dealerGroups).map(([dealerName, expenseProvisions]) => (
        <View
          key={dealerName}
          className="border-b border-gray-100 last:border-b-0"
        >
          <View
            className="flex cursor-pointer items-center justify-between p-2.5"
            onClick={() => toggleGroup(dealerName)}
          >
            <View className="flex items-center">
              <View className="bg-primary/10 flex h-8 w-8 items-center justify-center rounded-full">
                <Icon name="building" className="text-primary" size={18} />
              </View>
              <View className="ml-2.5">
                <View className="text-neutral-darkest text-sm font-medium">
                  {dealerName} ({expenseProvisions.length}车)
                </View>
                <View className="text-neutral-darker text-xs">
                  总计提: {getDealerTotal(expenseProvisions).toLocaleString()}元
                </View>
              </View>
            </View>
            <Icon
              name={expandedGroups[dealerName] ? "chevron-up" : "chevron-down"}
              size={18}
            />
          </View>

          {/* 展开内容 */}
          {expandedGroups[dealerName] && (
            <View className="bg-gray-50 p-2.5">
              <View className="mb-2">
                <View className="text-neutral-darker mb-1 text-xs font-medium">
                  车次明细:
                </View>
                {expenseProvisions.map((expenseProvision, index) => (
                  <ExpenseProvisionCard
                    key={expenseProvision.expenseProvisionId}
                    expenseProvision={expenseProvision}
                    onUpdate={(updatedProvision) => {
                      onChange?.({
                        ...expenseRecord!,
                        expenseProvisionList: expenseProvisions.map((item) =>
                          item.expenseProvisionId ===
                          updatedProvision.expenseProvisionId
                            ? updatedProvision
                            : item,
                        ),
                      });
                    }}
                    onDelete={() => {
                      onChange?.({
                        ...expenseRecord!,
                        expenseProvisionList: expenseProvisions.filter(
                          (item) =>
                            item.expenseProvisionId !==
                            expenseProvision.expenseProvisionId,
                        ),
                      });
                    }}
                    index={index}
                  />
                ))}
              </View>
              <View className="border-t border-gray-100 pt-2.5">
                <View className="text-neutral-darkest flex flex-row text-sm font-medium">
                  该客户合计:
                  <View className="text-primary">
                    {getDealerTotal(expenseProvisions).toLocaleString()}元
                  </View>
                </View>
              </View>
            </View>
          )}
        </View>
      ))}

      {/* 总计区域 */}
      <View className="bg-gray-50 p-2.5">
        <View className="flex items-center justify-between">
          <View className="text-neutral-darker text-sm">计提总金额</View>
          <View className="text-primary text-lg font-semibold">
            {(expenseRecord?.totalProvision || 0).toLocaleString()}元
          </View>
        </View>
      </View>

      <View className={"bg-gray-50 p-2.5"}>
        <Button
          type="primary"
          size={"large"}
          block
          icon={<Icon name="plus" color={"white"} size={16} />}
          onClick={() => setVisible(true)}
        >
          添加计提车次
        </Button>
      </View>
      <ExpenseProvisionCreate
        visible={visible}
        onClose={() => setVisible(false)}
        onFinish={(expenseProvision) => {
          onChange?.({
            ...expenseRecord!,
            expenseProvisionList: [
              ...(expenseRecord?.expenseProvisionList || []),
              expenseProvision,
            ],
          });
        }}
      />
    </View>
  );
}
