import { convertOrderPackagesToBoxBrands } from "@/utils";
import { View } from "@tarojs/components";
import { Button } from "@nutui/nutui-react-taro";
import { Icon, PackageCard, PackageCreate } from "@/components";
import { useState } from "react";
import { BoxBrand } from "@/types/typings";

interface IPackageListProps {
  boxType: BusinessAPI.OrderPackage["boxType"];
  orderPackageList: BusinessAPI.OrderPackage[];
  boxBrandList?: BoxBrand[];
  setOrderPackageList: (orderPackageList: BusinessAPI.OrderPackage[]) => void;
}

export default function PackageList(props: IPackageListProps) {
  const { boxType, orderPackageList, boxBrandList, setOrderPackageList } =
    props;

  // 批量添加纸箱弹窗状态
  const [showBatchModal, setShowBatchModal] = useState(false);

  // 获取该类型下所有的纸箱
  const packagesOfType = convertOrderPackagesToBoxBrands(
    orderPackageList?.filter((pkg) => pkg.boxType === boxType),
  );

  // 根据类型设置显示标题
  const typeLabels = {
    USED: "装车用的纸箱",
    EXTRA_USED: "用的额外运输纸箱",
    EXTRA: "额外运输来的所有纸箱",
    REMAIN: "车上没用完的纸箱",
    EMPTY: "空箱",
  };

  if (!boxBrandList) {
    return;
  }

  return (
    <>
      <View className="flex items-center justify-between">
        <View className="text-base font-bold text-gray-800">
          记录{typeLabels[boxType]}
        </View>
      </View>

      {packagesOfType.length > 0 ? (
        packagesOfType.map((boxBrand, index) => (
          <PackageCard
            key={index}
            boxBrand={boxBrand}
            boxBrandList={boxBrandList}
            boxType={boxType}
            orderPackageList={orderPackageList}
            setOrderPackageList={setOrderPackageList}
          />
        ))
      ) : (
        <View className="rounded-lg bg-gray-50 p-4 text-center text-gray-500">
          还没有记录{typeLabels[boxType]}
        </View>
      )}

      <Button
        icon={<Icon name={"plus"} size={20} />}
        type={"primary"}
        size={"large"}
        fill={"outline"}
        block
        className="border-primary text-primary flex w-full items-center justify-center !border-2 !bg-white"
        onClick={() => {
          setShowBatchModal(true);
        }}
      >
        <View>记录{typeLabels[boxType]}</View>
      </Button>

      <PackageCreate
        boxType={boxType}
        boxBrandList={boxBrandList}
        orderPackageList={orderPackageList}
        visible={showBatchModal}
        onClose={() => setShowBatchModal(false)}
        onSave={setOrderPackageList}
      />
    </>
  );
}
