import { Label, Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { buildUrl } from "@/utils";
import { CopyText, Icon, State } from "@/components";
import order from "@/constant/order";
import dayjs from "dayjs";
import { Button, Dialog, Progress, Toast } from "@nutui/nutui-react-taro";
import { business } from "@/services";
import { purchase } from "@/constant";
import classNames from "classnames";
import { useState } from "react";

interface IOrderItemProps {
  orderVO: BusinessAPI.OrderVO;
  actionRef: any;
}

export default function OrderItem(props: IOrderItemProps) {
  const { orderVO, actionRef } = props;

  // 进度条展开状态
  const [progressExpanded, setProgressExpanded] = useState(false);

  // 格式化步骤标题
  const formatStepTitle = (title: string): string => {
    return title.replace(/步骤 \d\/\{\}: /, "").replace("步骤 ", "");
  };

  // 计算进度信息
  const getProgressInfo = () => {
    const steps =
      orderVO.type === "PRODUCTION_PURCHASE"
        ? purchase.madeSteps
        : purchase.marketSteps;
    const totalSteps = steps.length - 1;
    let active = orderVO.active || 1;
    if (active > totalSteps) {
      active = totalSteps;
    }
    const currentStep = active;
    const progress = Math.round((currentStep / totalSteps) * 100);
    const remainingSteps = totalSteps - currentStep;

    return {
      currentStep,
      totalSteps,
      progress,
      remainingSteps,
      isCompleted: currentStep === totalSteps,
      steps: steps.map((step) => ({
        ...step,
        formattedTitle: formatStepTitle(step.title),
        completed: step.value < currentStep,
        current: step.value === currentStep,
        isDisabled: step.value > totalSteps,
      })),
    };
  };

  // 删除采购订单
  const handleDelete = (orderVO: BusinessAPI.OrderVO) => {
    Dialog.open("dialog", {
      title: "删除采购单",
      content: `确定要删除这个采购单吗？删除后就找不回来了！`,
      confirmText: "确定",
      cancelText: "取消",
      onConfirm: async () => {
        try {
          const { data } = await business.order.destroyOrder({
            orderId: orderVO.orderId,
          });

          if (data.success) {
            Toast.show("toast", {
              icon: "success",
              title: "提示",
              content: "采购单删除成功",
            });
            actionRef.current?.reload();
          } else {
            Toast.show("toast", {
              icon: "fail",
              title: "提示",
              content: data.errMessage || "删除失败",
            });
          }
        } catch (error) {
          Toast.show("toast", {
            icon: "fail",
            title: "提示",
            content: "删除失败",
          });
        } finally {
          Dialog.close("dialog");
        }
      },
      onCancel: () => {
        Dialog.close("dialog");
      },
    });
  };

  return (
    <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={(event) => {
          if (purchase.isPreview(orderVO) || orderVO.state !== "DRAFT") {
            Taro.navigateTo({
              url: buildUrl(purchase.path[orderVO.type].preview, {
                orderId: orderVO.orderId,
              }),
            });
            event.stopPropagation();
          }
        }}
      >
        <View className={"flex min-w-0 flex-1 flex-col gap-1.5"}>
          <Text className={"text-neutral-darkest truncate text-lg font-bold"}>
            {orderVO.orderVehicle?.dealerName}{" "}
            {orderVO.orderVehicle?.vehicleNo
              ? `第${orderVO.orderVehicle?.vehicleNo}车`
              : "暂未生成车次"}
          </Text>
          <Text className={"text-neutral-dark truncate text-xs"}>
            {`${orderVO.orderVehicle?.origin} → ${orderVO.orderVehicle?.destination}`}
          </Text>
        </View>
        <View className={"flex flex-col items-end gap-1"}>
          {orderVO.state === "AUDITING" ? (
            <State
              state={orderVO.auditState}
              stateMap={order.auditStateMap}
              position={"relative"}
            />
          ) : (
            <State
              state={orderVO.state}
              stateMap={order.stateMap}
              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>

      {/* 进度条区域 - 仅在草稿状态显示 */}
      {orderVO.state === "DRAFT" && (
        <View
          className={
            "border-y border-blue-100 bg-gradient-to-r from-blue-50 to-indigo-50"
          }
        >
          {/* 进度条头部 - 始终显示，可点击展开/收起 */}
          <View
            className={
              "flex cursor-pointer items-center justify-between px-4 py-3"
            }
            onClick={() => setProgressExpanded(!progressExpanded)}
          >
            <View className={"flex items-center gap-2"}>
              <Text className={"text-sm font-semibold text-gray-700"}>
                填写进度
              </Text>
              <Text
                className={classNames(
                  "text-sm font-bold",
                  getProgressInfo().isCompleted
                    ? "text-green-600"
                    : "text-blue-600",
                )}
              >
                {getProgressInfo().currentStep}/{getProgressInfo().totalSteps}
                <Text className={"font-normal text-gray-500"}>
                  {" "}
                  ({getProgressInfo().progress}%)
                </Text>
              </Text>
            </View>
            <Icon
              name={progressExpanded ? "chevron-up" : "chevron-down"}
              size={16}
              className={"text-gray-500"}
            />
          </View>

          {/* 展开的详细内容 */}
          {progressExpanded && (
            <View className={"border-t border-blue-100 px-4 pt-2 pb-3"}>
              <Progress
                percent={getProgressInfo().progress}
                color={
                  getProgressInfo().isCompleted
                    ? "#10B981"
                    : getProgressInfo().progress > 50
                      ? "#3B82F6"
                      : "#F59E0B"
                }
                strokeWidth={"6"}
                showText={false}
              />
              {getProgressInfo().remainingSteps > 0 && (
                <View className={"mt-2 flex flex-wrap items-center gap-1.5"}>
                  <Text className={"text-xs text-gray-500"}>待填写：</Text>
                  {getProgressInfo()
                    .steps.filter(
                      (step) =>
                        !step.completed && !step.current && !step.isDisabled,
                    )
                    .map((step) => (
                      <View
                        key={step.value}
                        className={classNames(
                          "rounded-full px-2 py-0.5 text-xs font-medium",
                          "border border-orange-200 bg-orange-100 text-orange-700",
                        )}
                      >
                        {step.formattedTitle}
                      </View>
                    ))}
                </View>
              )}
              {getProgressInfo().isCompleted && (
                <View className={"mt-2 flex items-center gap-1"}>
                  <View
                    className={
                      "rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700"
                    }
                  >
                    ✓ 所有步骤已完成
                  </View>
                  <Text className={"text-xs text-gray-500"}>可提交审核</Text>
                </View>
              )}
            </View>
          )}
        </View>
      )}

      {/* 详细信息区域 */}
      <View
        className={"flex cursor-pointer flex-col gap-2 px-4 py-3"}
        onClick={(event) => {
          if (purchase.isPreview(orderVO)) {
            Taro.navigateTo({
              url: buildUrl(purchase.path[orderVO.type].preview, {
                orderId: orderVO.orderId,
              }),
            });
            event.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"}>
            {dayjs(orderVO.createdAt).format("MM-DD HH:mm")}
          </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(orderVO.orderVehicle?.deliveryTime).format("YYYY年MM月DD日")}
          </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"}>
            {orderVO.orderVehicle?.driver}（{orderVO.orderVehicle?.plate}）
          </Text>
        </View>
        <View className={"flex flex-row items-center justify-between"}>
          <Label className={"text-neutral-dark text-xs"}>
            {purchase.supplierSlug[orderVO.type]}信息
          </Label>
          <Text className={"text-neutral-darkest text-xs font-medium"}>
            {orderVO.orderSupplierList.map((item) => item.name).join("、")}
          </Text>
        </View>
      </View>

      {/* 操作按钮区域 */}
      <View
        className={
          "flex justify-end gap-2 border-t border-neutral-100 bg-gray-50 px-4 py-3"
        }
      >
        {/* 删除 */}
        {orderVO.state === "DRAFT" && (
          <Button
            type={"danger"}
            size={"small"}
            onClick={(e) => {
              handleDelete(orderVO);
              e.stopPropagation();
            }}
          >
            删除
          </Button>
        )}

        {orderVO.orderVehicle?.phone && (
          <Button
            type={"default"}
            size={"small"}
            onClick={(e) => {
              Taro.makePhoneCall({
                phoneNumber: orderVO.orderVehicle.phone as string,
              });
              e.stopPropagation();
            }}
          >
            联系司机
          </Button>
        )}

        {orderVO.state === "DRAFT" && (
          <>
            <Button
              type={"default"}
              size={"small"}
              onClick={(e) => {
                Taro.navigateTo({
                  url: buildUrl(purchase.path[orderVO.type].create, {
                    orderId: orderVO.orderId,
                  }),
                });
                e.stopPropagation();
              }}
            >
              编辑
            </Button>

            {purchase.isPreview(orderVO) && (
              <Button
                type={"primary"}
                size={"small"}
                onClick={(e) => {
                  Taro.navigateTo({
                    url: buildUrl(purchase.path[orderVO.type].preview, {
                      orderId: orderVO.orderId,
                    }),
                  });
                  e.stopPropagation();
                }}
              >
                提交审核
              </Button>
            )}
          </>
        )}

        {/*{orderVO.state === "AUDITING" && (*/}
        {/*  <Button*/}
        {/*    type={"primary"}*/}
        {/*    size={"small"}*/}
        {/*    onClick={(e) => {*/}
        {/*      Taro.navigateTo({*/}
        {/*        url: buildUrl(purchase.path[orderVO.type].result, {*/}
        {/*          orderId: orderVO.orderId,*/}
        {/*        }),*/}
        {/*      });*/}
        {/*      e.stopPropagation();*/}
        {/*    }}*/}
        {/*  >*/}
        {/*    审核进度*/}
        {/*  </Button>*/}
        {/*)}*/}
      </View>
    </View>
  );
}
