import {
  ActionType,
  CopyText,
  DealerPicker,
  Icon,
  OrderRejectFinal,
  PageList,
  State,
  SupplierPicker,
  ToolBar,
} from "@/components";
import React, { useRef, useState } from "react";
import { business } from "@/services";
import { Label, Text, View } from "@tarojs/components";
import { buildUrl } from "@/utils";
import { Button } from "@nutui/nutui-react-taro";
import dayjs from "dayjs";
import Taro from "@tarojs/taro";
import audit from "@/constant/audit";
import classNames from "classnames";
import { globalStore } from "@/store/global-store";

interface IApprovalListProps {
  params: BusinessAPI.AuditPageQry;
  toolbar?: ToolBar<BusinessAPI.AuditVO>;
  actionRef?: React.MutableRefObject<ActionType | undefined>;
}

export default function ApprovalList(props: IApprovalListProps) {
  const {
    params: bizParams,
    toolbar: defaultToolbar,
    actionRef: externalActionRef,
  } = props;

  const userRoleVO = globalStore((state: any) => state.userRoleVO);
  const internalActionRef = useRef<ActionType>();
  const actionRef = externalActionRef || internalActionRef;
  const [dealerVO, setDealerVO] = useState<BusinessAPI.DealerVO>();
  const [supplierVO, setSupplierVO] = useState<BusinessAPI.SupplierVO>();
  const toolbar: ToolBar<BusinessAPI.AuditVO> = {
    ...defaultToolbar,
    search: {
      activeKey: "plate",
      defaultActiveKey: "plate",
      items: [
        {
          key: "plate",
          name: "车牌号",
          placeholder: "请输入车牌号",
        },
      ],
    },
    render: () => (
      <View className={"item-start flex flex-row gap-2.5"}>
        <View>
          <DealerPicker
            onFinish={(dealerVO) => {
              setDealerVO(dealerVO);
              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"}>
                  {dealerVO?.shortName || "经销商"}
                </View>
                {dealerVO?.shortName ? (
                  <Icon
                    name={"circle-xmark"}
                    size={16}
                    onClick={(event) => {
                      setDealerVO(undefined);
                      actionRef.current?.reload();
                      event.stopPropagation();
                    }}
                  />
                ) : (
                  <Icon name={"chevron-down"} size={16} />
                )}
              </View>
            }
          />
        </View>
        <View>
          <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>
      </View>
    ),
  };

  return (
    <PageList<BusinessAPI.AuditVO, BusinessAPI.AuditPageQry>
      rowId={"orderId"}
      itemHeight={182}
      toolbar={toolbar}
      type={"infinite"}
      actionRef={actionRef}
      render={(auditVO: BusinessAPI.AuditVO, index) => {
        const orderVO = auditVO.orderVO;
        return (
          orderVO && (
            <View className={"mb-2"} key={index}>
              <View
                className={
                  "relative flex flex-col divide-y divide-neutral-100 overflow-hidden rounded-xl bg-white shadow-sm"
                }
              >
                {/* 头部区域：标题 + 类型 + 状态 */}
                <View
                  className={
                    "flex cursor-pointer items-center justify-between gap-2 px-4 py-3"
                  }
                  onClick={(e) => {
                    if (
                      auditVO.state === "WAITING_AUDIT" &&
                      auditVO.type === "BOSS_AUDIT"
                    ) {
                      Taro.navigateTo({
                        url: buildUrl("/pages/approval/audit", {
                          orderId: orderVO.orderId,
                          auditId: auditVO.auditId,
                        }),
                      });
                      e.stopPropagation();
                    }
                  }}
                >
                  <View className={"flex min-w-0 flex-1 flex-col gap-1.5"}>
                    <Text className={"text-neutral-darkest text-lg font-bold"}>
                      {orderVO.orderVehicle?.dealerName}
                      {orderVO.orderVehicle?.vehicleNo
                        ? `第${orderVO.orderVehicle?.vehicleNo}车`
                        : "暂未生成车次"}
                    </Text>
                    <Text className={"text-neutral-dark text-xs"}>
                      {`${orderVO.orderVehicle?.origin} → ${orderVO.orderVehicle?.destination}`}
                    </Text>
                  </View>
                  <View className={"flex flex-col items-end gap-1"}>
                    <State
                      state={auditVO.state}
                      stateMap={audit.approvalStateMap}
                      position={"relative"}
                    />
                    <Text
                      className={classNames(
                        "rounded px-2 py-0.5 text-xs font-medium",
                        orderVO.type === "PRODUCTION_PURCHASE"
                          ? "bg-purple-100 text-purple-700"
                          : "bg-cyan-100 text-cyan-700",
                      )}
                    >
                      {orderVO.type === "PRODUCTION_PURCHASE"
                        ? "产地采购"
                        : "市场采购"}
                    </Text>
                  </View>
                </View>

                {/* 详细信息区域 */}
                <View
                  className={"flex cursor-pointer flex-col gap-2 px-4 py-3"}
                  onClick={(e) => {
                    if (
                      auditVO.state === "WAITING_AUDIT" &&
                      auditVO.type === "BOSS_AUDIT"
                    ) {
                      Taro.navigateTo({
                        url: buildUrl("/pages/approval/audit", {
                          orderId: orderVO.orderId,
                          auditId: auditVO.auditId,
                        }),
                      });
                      e.stopPropagation();
                    }
                  }}
                >
                  <View
                    className={"flex flex-row items-center justify-between"}
                  >
                    <Label className={"text-neutral-dark text-xs"}>
                      采购单号
                    </Label>
                    <CopyText copyData={orderVO?.orderSn || "-"}>
                      <Text
                        className={"text-neutral-darkest text-xs font-medium"}
                      >
                        {orderVO.orderSn}
                      </Text>
                    </CopyText>
                  </View>
                  <View
                    className={"flex flex-row items-center justify-between"}
                  >
                    <Label className={"text-neutral-dark text-xs"}>
                      提交人
                    </Label>
                    <Text
                      className={"text-neutral-darkest text-xs font-medium"}
                    >
                      {auditVO.createdByName}
                    </Text>
                  </View>
                  <View
                    className={"flex flex-row items-center justify-between"}
                  >
                    <Label className={"text-neutral-dark text-xs"}>
                      提交时间
                    </Label>
                    <Text
                      className={"text-neutral-darkest text-xs font-medium"}
                    >
                      {dayjs(auditVO.createdAt).format("MM-DD HH:mm")}
                    </Text>
                  </View>
                  {auditVO.state === "AUDIT_REJECTED" && (
                    <>
                      <View
                        className={"flex flex-row items-center justify-between"}
                      >
                        <Label className={"text-neutral-dark text-xs"}>
                          驳回人
                        </Label>
                        <Text
                          className={"text-neutral-darkest text-xs font-medium"}
                        >
                          {auditVO.auditByName}
                        </Text>
                      </View>
                      <View
                        className={"flex flex-row items-center justify-between"}
                      >
                        <Label className={"text-neutral-dark text-xs"}>
                          驳回时间
                        </Label>
                        <Text
                          className={"text-neutral-darkest text-xs font-medium"}
                        >
                          {dayjs(auditVO.auditAt).format("MM-DD HH:mm")}
                        </Text>
                      </View>
                      {auditVO.auditReason && (
                        <View className={"mt-1 rounded-lg bg-red-50 p-2.5"}>
                          <Text className={"text-xs font-medium text-red-700"}>
                            驳回理由：{auditVO.auditReason}
                          </Text>
                        </View>
                      )}
                    </>
                  )}
                </View>

                {/* 操作按钮区域 */}
                <View
                  className={
                    "flex justify-end gap-2 border-t border-neutral-100 bg-gray-50 px-4 py-3"
                  }
                >
                  {auditVO.state === "WAITING_AUDIT" &&
                    auditVO.type === "BOSS_AUDIT" &&
                    userRoleVO.slug === "boss" && (
                      <>
                        <View className={"flex-1"}>
                          <OrderRejectFinal
                            auditVO={auditVO}
                            size={"small"}
                            onFinish={() => {
                              actionRef.current?.reload();
                            }}
                          />
                        </View>
                        <View className={"flex-1"}>
                          <Button
                            type={"primary"}
                            size={"small"}
                            block
                            onClick={(e) => {
                              Taro.navigateTo({
                                url: buildUrl("/pages/approval/audit", {
                                  orderId: orderVO.orderId,
                                  auditId: auditVO.auditId,
                                }),
                              });
                              e.stopPropagation();
                            }}
                          >
                            前往审批
                          </Button>
                        </View>
                      </>
                    )}

                  {auditVO.state === "AUDIT_REJECTED" &&
                    auditVO.type === "BOSS_AUDIT" &&
                    userRoleVO.slug === "reviewer" && (
                      <>
                        <Button
                          type={"primary"}
                          size={"small"}
                          block
                          onClick={(e) => {
                            Taro.navigateTo({
                              url: buildUrl("/pages/audit/audit", {
                                orderId: orderVO.orderId,
                                auditId: auditVO.auditId,
                              }),
                            });
                            e.stopPropagation();
                          }}
                        >
                          重新编辑
                        </Button>
                      </>
                    )}
                  {auditVO.state === "AUDIT_SUCCESS" &&
                    auditVO.type === "BOSS_AUDIT" &&
                    userRoleVO.slug === "boss" && (
                      <>
                        <Button
                          type={"primary"}
                          size={"small"}
                          block
                          onClick={(e) => {
                            Taro.navigateTo({
                              url: buildUrl("/pages/approval/audit", {
                                orderId: orderVO.orderId,
                                auditId: auditVO.auditId,
                              }),
                            });
                            e.stopPropagation();
                          }}
                        >
                          查看审批
                        </Button>
                      </>
                    )}
                </View>
              </View>
            </View>
          )
        );
      }}
      request={async (params) => {
        const {
          data: { data, success, notEmpty },
        } = await business.audit.pageAudit({
          auditPageQry: {
            ...params,
            ...bizParams,
          },
        });

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