import { ActionType, Icon, PageList, Phone, ToolBar } from "@/components";
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { useRef } from "react";
import { business } from "@/services";
import hocAuth from "@/hocs/auth";
import { CommonComponent } from "@/types/typings";
import { Label, Text, View } from "@tarojs/components";
import dayjs from "dayjs";
import { buildUrl } from "@/utils";
import { Button } from "@nutui/nutui-react-taro";

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

  const actionRef = useRef<ActionType>();
  const toolbar: ToolBar<BusinessAPI.SupplierVO> = {
    search: {
      activeKey: "name",
      defaultActiveKey: "name",
      items: [
        {
          key: "name",
          name: "瓜农名称",
          placeholder: "请输入瓜农名称",
        },
      ],
    },
    actions: [
      <View className={"flex flex-row gap-2 p-3"} key={"create"}>
        <View className={"flex-1"}>
          <View
            className="bg-primary flex w-full flex-col items-center justify-center space-y-2 rounded-xl py-2.5 text-white"
            onClick={() => {
              Taro.navigateTo({
                url: buildUrl("/pages/supplier/create"),
              });
            }}
          >
            <View className="text-base font-bold">登记瓜农</View>
          </View>
        </View>
      </View>,
    ],
  };

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

  return (
    <PageList<BusinessAPI.SupplierVO, BusinessAPI.SupplierPageQry>
      rowId={"supplierId"}
      itemHeight={182}
      type={"infinite"}
      actionRef={actionRef}
      render={(supplierVO: BusinessAPI.SupplierVO, index) => (
        <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={() => {
                Taro.navigateTo({
                  url: buildUrl("/pages/supplier/create", {
                    supplierId: supplierVO.supplierId,
                  }),
                });
              }}
            >
              <View className={"flex min-w-0 flex-1 flex-col gap-1.5"}>
                <Text className={"text-neutral-darkest text-lg font-bold"}>
                  {supplierVO?.name}
                </Text>
                <Text className={"text-neutral-dark text-xs"}>
                  瓜农 ID: {supplierVO.supplierId}
                </Text>
              </View>
              <Button
                size={"small"}
                type={"primary"}
                fill={"none"}
                icon={<Icon name={"pen-to-square"} size={16} />}
                onClick={(e) => {
                  e.stopPropagation();
                  Taro.navigateTo({
                    url: buildUrl("/pages/supplier/create", {
                      supplierId: supplierVO.supplierId,
                    }),
                  });
                }}
              />
            </View>

            {/* 详细信息区域 */}
            <View
              className={"flex cursor-pointer flex-col gap-2 px-4 py-3"}
              onClick={() => {
                Taro.navigateTo({
                  url: buildUrl("/pages/supplier/create", {
                    supplierId: supplierVO.supplierId,
                  }),
                });
              }}
            >
              <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(supplierVO.createdAt).format("YYYY-MM-DD HH:mm")}
                </Text>
              </View>
              <View className={"flex flex-row items-center justify-between"}>
                <Label className={"text-neutral-dark text-xs"}>联系方式</Label>
                <View
                  className={
                    "flex flex-1 flex-row items-center justify-end gap-1"
                  }
                >
                  {supplierVO.phone && <Phone phone={supplierVO.phone} />}
                </View>
              </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"}>
                  已开票 12 张 | 待开票 2 张
                </Text>
              </View>
            </View>

            {/* 操作按钮区域 */}
            <View
              className={
                "flex justify-end gap-2 border-t border-neutral-100 bg-gray-50 px-4 py-3"
              }
            >
              {supplierVO.phone && (
                <Button
                  size={"small"}
                  type={"default"}
                  onClick={(e) => {
                    e.stopPropagation();
                    Taro.makePhoneCall({
                      phoneNumber: supplierVO.phone!,
                    });
                  }}
                >
                  联系
                </Button>
              )}
              <Button
                size={"small"}
                type={"default"}
                onClick={(e) => {
                  e.stopPropagation();
                  Taro.navigateTo({
                    url: buildUrl("/pages/purchase/made/create", {
                      supplierId: supplierVO.supplierId,
                    }),
                  });
                }}
              >
                新建采购
              </Button>
              <Button
                size={"small"}
                type={"primary"}
                onClick={(e) => {
                  e.stopPropagation();
                  Taro.navigateTo({
                    url: buildUrl("/pages/invoice/upload", {
                      supplierId: supplierVO.supplierId,
                    }),
                  });
                }}
              >
                协助开票
              </Button>
            </View>
          </View>
        </View>
      )}
      toolbar={toolbar}
      request={async (params) => {
        const {
          data: { data, success, notEmpty },
        } = await business.supplier.pageSupplier({
          supplierPageQry: {
            ...params,
            type: "FARMER",
          },
        });

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