import {
  ActionType,
  Icon,
  PageList,
  State,
  SupplierPicker,
  ToolBar,
} from "@/components";
import React, { useEffect, useRef, useState } from "react";
import { DecimalUtils } from "@/utils/classes/calculators/core/DecimalUtils";
import { Text, View } from "@tarojs/components";
import { Button, Checkbox, Popup } from "@nutui/nutui-react-taro";
import classNames from "classnames";
import dayjs from "dayjs";
import order from "@/constant/order";
import { business } from "@/services";

interface IOrderSupplierPickerProps {
  value: BusinessAPI.OrderSupplierVO[];
  onFinish: (orderSupplierList: BusinessAPI.OrderSupplierVO[]) => void;
  trigger: React.ReactNode;
}

export default function OrderSupplierPicker(props: IOrderSupplierPickerProps) {
  const { value, trigger, onFinish } = props;
  const [visible, setVisible] = useState(false);
  const [orderSupplierList, setOrderSupplierList] = useState<
    BusinessAPI.OrderSupplierVO[]
  >([]);
  // 瓜农
  const [supplierVO, setSupplierVO] = useState<BusinessAPI.SupplierVO>();
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  useEffect(() => {
    setOrderSupplierList(value);
    setSelectedIds(new Set(value.map((item) => item.orderSupplierId)));
  }, [value]);

  const actionRef = useRef<ActionType>();

  // 切换选中状态
  const toggleSelect = (orderSupplierVO: BusinessAPI.OrderSupplierVO) => {
    const newSelectedIds = new Set(selectedIds);
    if (newSelectedIds.has(orderSupplierVO.orderSupplierId)) {
      newSelectedIds.delete(orderSupplierVO.orderSupplierId);
      setOrderSupplierList(
        orderSupplierList.filter(
          (orderSupplierVO) =>
            orderSupplierVO.orderSupplierId !== orderSupplierVO.orderSupplierId,
        ),
      );
    } else {
      newSelectedIds.add(orderSupplierVO.orderSupplierId);
      setOrderSupplierList([...orderSupplierList, orderSupplierVO]);
    }
    setSelectedIds(newSelectedIds);
  };

  // 全选/取消全选
  const toggleSelectAll = (allIds: string[]) => {
    if (selectedIds.size === allIds.length) {
      // 取消全选
      setSelectedIds(new Set());
    } else {
      // 全选
      setSelectedIds(new Set(allIds));
    }
  };

  // 计算选中订单的总重量和总金额
  const calculateSelectedTotals = (data: BusinessAPI.OrderSupplierVO[]) => {
    const selected = data.filter((item) =>
      selectedIds.has(item.orderSupplierId),
    );
    return selected.reduce(
      (totals, order) => {
        totals.totalWeight = DecimalUtils.add(
          totals.totalWeight,
          order.netWeight || 0,
        );
        totals.totalAmount = DecimalUtils.add(
          totals.totalAmount,
          order.invoiceAmount || 0,
        );
        return totals;
      },
      { totalWeight: 0, totalAmount: 0 },
    );
  };

  const toolbar: ToolBar<BusinessAPI.OrderSupplierVO> = {
    search: {
      activeKey: "vehicleNo",
      defaultActiveKey: "vehicleNo",
      items: [
        {
          key: "vehicleNo",
          name: "车次号",
          placeholder: "请输入车次号",
        },
        {
          key: "plate",
          name: "车牌号",
          placeholder: "请输入车牌号",
        },
      ],
    },
    render: () => {
      return (
        <>
          <View className={"flex flex-row gap-2.5"}>
            <SupplierPicker
              type={"FARMER"}
              onFinish={(supplierVO) => {
                setSupplierVO(supplierVO);
                actionRef.current?.reload();
              }}
              trigger={
                <View
                  className={`border-primary flex h-6 items-center rounded-md border-2 px-2.5`}
                >
                  <View className={"text-primary text-xs"}>
                    {supplierVO?.name || "瓜农"}
                  </View>
                  {supplierVO?.name ? (
                    <Icon
                      name={"circle-xmark"}
                      size={16}
                      onClick={(event) => {
                        setSupplierVO(undefined);
                        actionRef.current?.reload();
                        event.stopPropagation();
                      }}
                    />
                  ) : (
                    <Icon name={"chevron-down"} size={16} />
                  )}
                </View>
              }
            />
          </View>
        </>
      );
    },
    footer: (data: BusinessAPI.OrderSupplierVO[]) => {
      const allIds = data.map((item) => item.orderSupplierId);
      const isSelectedAll =
        selectedIds.size === allIds.length && allIds.length > 0;
      const totals = calculateSelectedTotals(data);
      return (
        <View className="sticky bottom-0 z-10 bg-white">
          {/* 批量操作栏 */}
          <View className="flex items-center justify-between p-2.5">
            {/* 全选按钮 */}
            {(selectedIds.size === 0 && data.length > 0 && (
              <View className="p-2.5">
                <View
                  className="flex cursor-pointer items-center gap-2 rounded-lg bg-gray-50 px-3 py-2"
                  onClick={() => toggleSelectAll(allIds)}
                >
                  <Checkbox checked={false} />
                  <Text className="text-sm text-gray-600">全选当前页</Text>
                </View>
              </View>
            )) || (
              <View className="flex flex-1 flex-row items-center gap-2">
                <Checkbox
                  checked={isSelectedAll}
                  onChange={() => toggleSelectAll(allIds)}
                />
                <View className="flex flex-col">
                  <Text className="text-sm font-medium text-gray-700">
                    已选 {selectedIds.size} 项
                  </Text>
                  <Text className="text-xs text-gray-500">
                    总重: {totals.totalWeight}斤 | 金额: ¥
                    {totals.totalAmount.toFixed(2)}
                  </Text>
                </View>
              </View>
            )}

            <View className="flex flex-row items-center gap-2">
              <Button
                type={"default"}
                size={"large"}
                onClick={() => {
                  setSelectedIds(new Set());
                }}
              >
                取消选择
              </Button>
              <Button
                type={"primary"}
                size={"large"}
                onClick={() => {
                  if (selectedIds.size > 0) {
                    const selected = data.filter((item) =>
                      selectedIds.has(item.orderSupplierId),
                    );
                    setOrderSupplierList(selected);
                    onFinish?.(selected);
                    setVisible(false);
                  } else {
                    setOrderSupplierList([]);
                    onFinish?.([]);
                    setVisible(false);
                  }
                }}
              >
                确认选择
              </Button>
            </View>
          </View>
        </View>
      );
    },
  };
  return (
    <>
      <View
        style={{
          color: "var(--nutui-color-title, #1a1a1a)",
        }}
        onClick={(event) => {
          setVisible(true);
          event.stopPropagation();
        }}
      >
        {trigger}
      </View>

      {/* 选择瓜农车次 */}
      <Popup
        duration={150}
        style={{
          minHeight: "auto",
        }}
        closeable
        destroyOnClose
        visible={visible}
        title="选择瓜农车次"
        position="bottom"
        onClose={async () => {
          if (visible) {
            setOrderSupplierList([]);
            setVisible(false);
          } else if (orderSupplierList) {
            onFinish(orderSupplierList);
          }
        }}
      >
        <PageList<BusinessAPI.OrderSupplierVO, BusinessAPI.OrderSupplierPageQry>
          rowId={"orderSupplierId"}
          itemHeight={100}
          type={"infinite"}
          actionRef={actionRef}
          render={(orderSupplierVO: BusinessAPI.OrderSupplierVO, index) => {
            const isSelected = selectedIds.has(orderSupplierVO.orderSupplierId);
            return (
              <View
                className={classNames("mb-2", isSelected && "p-0.5")}
                key={index}
              >
                <View
                  className={classNames(
                    "relative flex flex-col divide-y divide-neutral-100 overflow-hidden rounded-lg bg-white shadow-sm transition-all",
                    isSelected && "ring-primary ring-2 ring-offset-1",
                  )}
                >
                  {/* 选中遮罩层 */}
                  {isSelected && (
                    <View className="bg-primary/5 pointer-events-none absolute inset-0 z-10" />
                  )}

                  {/* 复选框 + 头部区域 */}
                  <View
                    className={
                      "flex cursor-pointer items-center justify-between gap-2 px-3 py-2"
                    }
                    onClick={(e) => {
                      // 点击卡片切换选中状态
                      e.stopPropagation();
                      toggleSelect(orderSupplierVO);
                    }}
                  >
                    <View className={"flex flex-1 flex-row items-center gap-2"}>
                      <Checkbox
                        checked={isSelected}
                        onClick={(e) => {
                          e.stopPropagation();
                          toggleSelect(orderSupplierVO);
                        }}
                      />
                      <View className={"flex min-w-0 flex-1 flex-col gap-1"}>
                        <Text
                          className={"text-neutral-darkest text-sm font-bold"}
                        >
                          {orderSupplierVO.name}
                        </Text>
                        <View className={"flex flex-row items-center gap-2"}>
                          <Text className={"text-neutral-dark text-xs"}>
                            {orderSupplierVO.orderVO?.orderVehicle?.origin} →{" "}
                            {orderSupplierVO.orderVO?.orderVehicle?.destination}
                          </Text>
                        </View>
                      </View>
                    </View>
                    <View className={"flex flex-col items-end gap-1"}>
                      {orderSupplierVO.poState && (
                        <State
                          position="relative"
                          state={orderSupplierVO.poState}
                          stateMap={order.stateMap}
                        />
                      )}
                      {/* 发票状态提示 */}
                      {orderSupplierVO.invoiceUpload ? (
                        <View className="flex items-center gap-1">
                          <Icon
                            name="check-circle"
                            size={10}
                            color={"#2E7D32"}
                          />
                          <Text className="text-xs text-green-700">已上传</Text>
                        </View>
                      ) : (
                        <View className="flex items-center gap-1">
                          <Icon name="clock" size={10} color={"#D97A05"} />
                          <Text className="text-xs text-orange-700">
                            待上传
                          </Text>
                        </View>
                      )}
                    </View>
                  </View>

                  {/* 详细信息区域 - 紧凑一行显示 */}
                  <View
                    className={
                      "flex flex-row items-center justify-between gap-2 px-3 py-2 text-xs"
                    }
                    onClick={(e) => {
                      // 点击详细信息区域也切换选中状态
                      e.stopPropagation();
                      toggleSelect(orderSupplierVO);
                    }}
                  >
                    <View
                      className={
                        "flex flex-1 flex-row items-center gap-1 text-gray-600"
                      }
                    >
                      <Text
                        className={classNames(
                          "text-xs font-medium",
                          "text-primary",
                        )}
                      >
                        {orderSupplierVO.orderVO?.orderVehicle?.vehicleNo
                          ? `第${orderSupplierVO.orderVO?.orderVehicle?.vehicleNo}车`
                          : "暂未生成车次"}
                      </Text>
                      |
                      <Text>
                        {dayjs(
                          orderSupplierVO.orderVO?.orderVehicle?.deliveryTime,
                        ).format("MM-DD")}
                      </Text>
                      <Text>|</Text>
                      <Text>{orderSupplierVO.netWeight}斤</Text>
                      <Text>|</Text>
                      <Text>¥{orderSupplierVO.invoiceAmount}</Text>
                    </View>
                    <Text className={"text-neutral-darkest font-medium"}>
                      {orderSupplierVO.productName}
                    </Text>
                  </View>
                </View>
              </View>
            );
          }}
          toolbar={toolbar}
          request={async (params) => {
            const {
              data: { data, success, notEmpty },
            } = await business.orderSupplier.pageOrderSupplier({
              orderSupplierPageQry: {
                ...params,
                invoiceUpload: false,
                poStates: ["AUDITING", "COMPLETED"],
                poType: "PRODUCTION_PURCHASE",
                supplierId: supplierVO?.supplierId,
              },
            });

            return {
              data,
              success,
              hasMore: notEmpty,
            };
          }}
          pagination={{
            pageSize: 10,
          }}
        />
      </Popup>
    </>
  );
}
