import {
  Icon,
  InvoiceCreate,
  OrderSupplierPicker,
  State,
  SupplierPicker,
} from "@/components";
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { useState } from "react";
import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { Text, View } from "@tarojs/components";
import { Button, SafeArea, Toast } from "@nutui/nutui-react-taro";
import classNames from "classnames";
import order from "@/constant/order";
import dayjs from "dayjs";
import { buildUrl } from "@/utils";

export default hocAuth(function Page(props: CommonComponent) {
  const { shareOptions } = props;

  const [visible, setVisible] = useState(false);
  // 发票开具人（有开发票资质的瓜农）
  const [invoiceIssuer, setInvoiceIssuer] = useState<BusinessAPI.SupplierVO>();

  const [orderSupplierList, setOrderSupplierList] = useState<
    BusinessAPI.OrderSupplierVO[]
  >([]);

  // 当前步骤：1-显示第一步和第二步，2-显示第三步
  const [currentStep, setCurrentStep] = useState<1 | 2>(1);
  // 错误状态
  const [invoiceIssuerError, setInvoiceIssuerError] = useState(false);
  const [orderSupplierError, setOrderSupplierError] = useState(false);

  useShareAppMessage((res) => {
    console.log("useShareAppMessage1", res, shareOptions);
    // 如果是按钮触发的转发，使用默认配置
    if (res.from === "button") {
      return shareOptions;
    }
    // 页面转发使用设置的配置
    return {};
  });

  // 计算开票类型
  const getInvoiceType = () => {
    if (!invoiceIssuer) {
      // 没有选择发票开具人，都是自开
      return "self";
    }

    // 检查车次中是否有可以自开的（瓜农自己就是发票开具人）
    const hasSelfInvoice = orderSupplierList.some(
      (item) => item.supplierId === invoiceIssuer.supplierId,
    );
    // 检查车次中需要代开的
    const hasProxyInvoice = orderSupplierList.some(
      (item) => item.supplierId !== invoiceIssuer.supplierId,
    );

    if (hasSelfInvoice && hasProxyInvoice) {
      return "both";
    } else if (hasSelfInvoice) {
      return "self";
    } else {
      return "proxy";
    }
  };

  const invoiceType = getInvoiceType();

  // 计算自开和代开金额
  const calculateInvoiceAmounts = () => {
    const selfInvoiceAmount = orderSupplierList
      .filter(
        (item) => invoiceIssuer && item.supplierId === invoiceIssuer.supplierId,
      )
      .reduce((sum, item) => sum + (item.invoiceAmount || 0), 0);

    const proxyInvoiceAmount = orderSupplierList
      .filter(
        (item) =>
          !invoiceIssuer || item.supplierId !== invoiceIssuer.supplierId,
      )
      .reduce((sum, item) => sum + (item.invoiceAmount || 0), 0);

    return {
      selfInvoiceAmount,
      proxyInvoiceAmount,
    };
  };

  const { selfInvoiceAmount, proxyInvoiceAmount } = calculateInvoiceAmounts();

  return (
    <>
      {/* 第一步和第二步 - 仅在步骤1时显示 */}
      {currentStep === 1 && (
        <View className={"flex flex-1 flex-col gap-2.5 bg-[#D1D5DB] p-2.5"}>
          {/* 发票开具人选择区域 */}
          <View className="text-sm font-medium text-gray-700">
            第一步：选择发票开具人
          </View>

          <View className={"rounded-md bg-white p-2.5 shadow-md"}>
            <SupplierPicker
              type={"FARMER"}
              onFinish={(supplierVO) => {
                setInvoiceIssuer(supplierVO);
                // 清除错误状态
                setInvoiceIssuerError(false);
              }}
              trigger={
                <View className={"flex flex-1 flex-row gap-2.5"}>
                  <View
                    className={`flex h-10 w-full items-center rounded-md border-4 ${
                      invoiceIssuerError ? "border-red-500" : "border-gray-300"
                    }`}
                  >
                    <View
                      className={
                        "flex flex-1 flex-row items-center justify-between px-5"
                      }
                    >
                      <View className={"text-sm"}>
                        {invoiceIssuer?.name || "请选择发票开具人"}
                      </View>
                      <Icon name={"chevron-down"} />
                    </View>
                  </View>
                </View>
              }
            />
            {invoiceIssuerError && (
              <View className="mt-2 text-xs text-red-500">
                请选择发票开具人
              </View>
            )}
          </View>

          {/* 需要代开发票的瓜农列表标题 */}
          <View className="text-sm font-medium text-gray-700">
            第二步：选择需要代开发票的瓜农车次
          </View>

          {orderSupplierList.map((orderSupplierVO, index) => {
            return (
              <View
                key={index}
                className={
                  "relative flex flex-col divide-y divide-neutral-100 overflow-hidden rounded-lg bg-white shadow-sm transition-all"
                }
              >
                {/* 复选框 + 头部区域 */}
                <View
                  className={
                    "flex cursor-pointer items-center justify-between gap-2 px-3 py-2"
                  }
                  onClick={(e) => {
                    // 点击卡片切换选中状态
                    e.stopPropagation();
                  }}
                >
                  <View className={"flex flex-1 flex-row items-center gap-2"}>
                    <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();
                  }}
                >
                  <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.dealerName}{" "}
                      {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>
            );
          })}

          <OrderSupplierPicker
            value={orderSupplierList}
            onFinish={(orderSupplierList: BusinessAPI.OrderSupplierVO[]) => {
              setOrderSupplierList(orderSupplierList);
              // 清除错误状态
              setOrderSupplierError(false);
            }}
            trigger={
              <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={() => {}}
              >
                <View>选择需要代开发票的瓜农车次</View>
              </Button>
            }
          />
          {orderSupplierError && (
            <View className="mt-2 text-xs text-red-500">
              请选择需要代开发票的瓜农车次
            </View>
          )}
        </View>
      )}

      {/* 第三步 - 仅在步骤2时显示 */}
      {currentStep === 2 && (
        <View className={"flex flex-1 flex-col gap-2.5 bg-[#D1D5DB] p-2.5"}>
          <View className="text-sm font-medium text-gray-700">
            第三步：预览代开发票信息
          </View>

          {/* 发票开具人信息卡片 */}
          {invoiceIssuer && (
            <View className="rounded-lg bg-white p-2.5 shadow-md">
              <View className="flex items-center justify-between">
                <View className="flex items-center gap-2">
                  <Text className="text-sm font-medium text-gray-600">
                    发票开具人
                  </Text>
                  <Text className="text-base font-bold text-gray-900">
                    {invoiceIssuer.name}
                  </Text>
                </View>
                <View className="rounded bg-blue-50 px-2 py-1">
                  <Text className="text-xs text-blue-600">代开方</Text>
                </View>
              </View>
            </View>
          )}

          {/* 本次登记开票概览卡片 */}
          <View className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-md">
            <Text className="text-sm font-bold text-gray-800">
              本次登记开票概览
            </Text>
            <View className="flex flex-wrap items-center gap-3 rounded-lg bg-gray-50 p-3">
              <View className="flex items-center gap-1">
                <Text className="text-xs text-gray-600">已选车次</Text>
                <Text className="text-primary text-base font-bold">
                  {orderSupplierList.length}
                </Text>
                <Text className="text-xs text-gray-600">次</Text>
              </View>
              <View className="h-4 w-px bg-gray-300" />
              <View className="flex items-center gap-1">
                <Text className="text-xs text-gray-600">总开票金额</Text>
                <Text className="text-primary text-base font-bold">
                  ¥
                  {orderSupplierList
                    .reduce((sum, item) => sum + (item.invoiceAmount || 0), 0)
                    .toFixed(2)}
                </Text>
              </View>
              <View className="h-4 w-px bg-gray-300" />
              <View className="flex items-center gap-1">
                <Text className="text-xs text-gray-600">开票类型</Text>
                <View
                  className={classNames(
                    "rounded px-2 py-0.5 text-xs font-medium",
                    invoiceType === "both"
                      ? "bg-blue-50 text-blue-600"
                      : invoiceType === "self"
                        ? "bg-green-50 text-green-600"
                        : "bg-orange-50 text-orange-600",
                  )}
                >
                  {invoiceType === "both"
                    ? "自开+代开"
                    : invoiceType === "self"
                      ? "自开"
                      : "代开"}
                </View>
              </View>
            </View>
          </View>

          {/* 车次开票明细卡片 */}
          {orderSupplierList.length > 0 && (
            <View className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-md">
              <Text className="text-sm font-bold text-gray-800">
                车次开票明细
              </Text>
              <View className="flex flex-col gap-2">
                {orderSupplierList.map((item, index) => {
                  // 判断该车次是自开还是代开
                  const isSelfInvoice =
                    invoiceIssuer &&
                    item.supplierId === invoiceIssuer.supplierId;
                  const isProxyInvoice =
                    invoiceIssuer &&
                    item.supplierId !== invoiceIssuer.supplierId;
                  const itemInvoiceType = !invoiceIssuer
                    ? "self"
                    : isSelfInvoice
                      ? "self"
                      : "proxy";

                  return (
                    <View
                      key={item.orderSupplierId || index}
                      className="rounded-lg border border-gray-200 p-3"
                    >
                      <View className="flex flex-col gap-2">
                        {/* 第一行：车次号 + 开票类型 */}
                        <View className="flex items-center justify-between">
                          <View className="flex items-center gap-2">
                            <Text className="text-xs text-gray-600">
                              {item.orderVO.orderVehicle.dealerName}{" "}
                              {item.orderVO?.orderVehicle?.vehicleNo
                                ? `第${item.orderVO.orderVehicle.vehicleNo}车`
                                : "未生成车次"}
                            </Text>
                            <View
                              className={classNames(
                                "rounded px-2 py-0.5 text-xs",
                                itemInvoiceType === "self"
                                  ? "bg-green-50 text-green-600"
                                  : "bg-orange-50 text-orange-600",
                              )}
                            >
                              {itemInvoiceType === "self" ? "自开" : "代开"}
                            </View>
                          </View>
                          <Text className="text-base font-bold text-gray-900">
                            ¥{item.invoiceAmount?.toFixed(2) || "0.00"}
                          </Text>
                        </View>
                        {/* 第二行：瓜农信息 */}
                        <View className="flex items-center justify-between text-xs">
                          <Text className="text-gray-600">
                            瓜农: {item.name}
                          </Text>
                          {isProxyInvoice && (
                            <Text className="text-gray-600">
                              开票方: {invoiceIssuer?.name}
                            </Text>
                          )}
                        </View>
                      </View>
                    </View>
                  );
                })}
              </View>
            </View>
          )}

          {/* 开票金额汇总卡片 */}
          <View className="flex flex-col gap-2.5 rounded-lg bg-white p-2.5 shadow-md">
            <Text className="text-sm font-bold text-gray-800">
              开票金额汇总
            </Text>
            <View className="flex flex-col gap-1.5 rounded-lg bg-gray-50 p-3">
              {/* 根据实际情况显示自开金额和代开金额 */}
              {selfInvoiceAmount > 0 && (
                <View className="flex items-center justify-between text-sm">
                  <Text className="text-gray-600">自开金额</Text>
                  <Text className="font-bold text-green-600">
                    ¥{selfInvoiceAmount.toFixed(2)}
                  </Text>
                </View>
              )}
              {proxyInvoiceAmount > 0 && (
                <View className="flex items-center justify-between text-sm">
                  <Text className="text-gray-600">代开金额</Text>
                  <Text className="font-bold text-orange-600">
                    ¥{proxyInvoiceAmount.toFixed(2)}
                  </Text>
                </View>
              )}
              {selfInvoiceAmount === 0 && (
                <View className="flex items-center justify-between text-sm">
                  <Text className="text-gray-600">自开金额</Text>
                  <Text className="font-medium text-gray-400">¥0.00</Text>
                </View>
              )}
              {proxyInvoiceAmount === 0 && (
                <View className="flex items-center justify-between text-sm">
                  <Text className="text-gray-600">代开金额</Text>
                  <Text className="font-medium text-gray-400">¥0.00</Text>
                </View>
              )}
              <View className="my-1 border-t border-dashed border-gray-300" />
              <View className="flex items-center justify-between">
                <Text className="font-bold text-gray-800">合计开票金额</Text>
                <Text className="text-primary text-lg font-bold">
                  ¥{(selfInvoiceAmount + proxyInvoiceAmount).toFixed(2)}
                </Text>
              </View>
            </View>
          </View>
        </View>
      )}

      <View className={"sticky bottom-0 z-10 flex flex-col gap-2.5 bg-white"}>
        <View className="flex justify-between gap-2 border-t border-gray-200 p-2.5">
          {/* 步骤1：显示返回首页和预览按钮 */}
          {currentStep === 1 && (
            <>
              <View className={"flex-1"}>
                <Button
                  block
                  type={"default"}
                  size={"large"}
                  onClick={() =>
                    Taro.switchTab({
                      url: buildUrl("/pages/main/index/index"),
                    })
                  }
                >
                  返回首页
                </Button>
              </View>
              <View className={"flex-1"}>
                <Button
                  block
                  type={"primary"}
                  size={"large"}
                  className="btn-large bg-primary ml-2 flex-1 text-white"
                  onClick={() => {
                    // 校验是否选择了发票开具人
                    if (!invoiceIssuer) {
                      setInvoiceIssuerError(true);
                      Toast.show("toast", {
                        icon: "fail",
                        title: "提示",
                        content: "请先选择发票开具人",
                      });
                      return;
                    }
                    // 校验是否选择了瓜农车次
                    if (!orderSupplierList || orderSupplierList.length === 0) {
                      setOrderSupplierError(true);
                      Toast.show("toast", {
                        icon: "fail",
                        title: "提示",
                        content: "请先选择需要代开发票的瓜农车次",
                      });
                      return;
                    }
                    // 切换到第三步
                    setCurrentStep(2);
                  }}
                >
                  代开预览
                </Button>
              </View>
            </>
          )}

          {/* 步骤2：显示上一步和上传发票按钮 */}
          {currentStep === 2 && (
            <>
              <View className={"flex-1"}>
                <Button
                  block
                  type={"default"}
                  size={"large"}
                  onClick={() => {
                    // 返回第一步和第二步
                    setCurrentStep(1);
                  }}
                >
                  上一步
                </Button>
              </View>
              <View className={"flex-1"}>
                <Button
                  block
                  type={"primary"}
                  size={"large"}
                  className="btn-large bg-primary ml-2 flex-1 text-white"
                  onClick={async () => {
                    // 打开发票上传弹窗
                    setVisible(true);
                  }}
                >
                  上传发票
                </Button>
              </View>
            </>
          )}
        </View>
        <SafeArea position={"bottom"} />
      </View>

      {/* Popup 弹窗 */}
      {invoiceIssuer && (
        <InvoiceCreate
          orderSupplierList={orderSupplierList}
          invoiceIssuer={invoiceIssuer}
          visible={visible}
          setVisible={setVisible}
          onFinish={() => {
            Taro.redirectTo({
              url: buildUrl("/pages/invoice/all"),
            });
          }}
        />
      )}
    </>
  );
});
