import hocAuth from "@/hocs/auth";
import { ActionType, PageList } from "@/components";
import { Text, View } from "@tarojs/components";
import { business } from "@/services";
import { useRef } from "react";
import { Button, Dialog, Toast } from "@nutui/nutui-react-taro";
import dayjs from "dayjs";
import classNames from "classnames";
import Taro from "@tarojs/taro";
import { buildUrl } from "@/utils";

export default hocAuth(function Page() {
  const actionRef = useRef<ActionType>();

  // 标记消息为已读
  const handleMarkAsRead = async (
    messageReceiver: BusinessAPI.MessageReceiverVO,
  ) => {
    if (messageReceiver.isRead) {
      return;
    }

    try {
      const { data } = await business.messageReceiver.markReadMessageReceiver({
        messageReceiverId: messageReceiver.messageReceiverId,
      });

      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: "操作失败",
      });
    }
  };

  // 删除消息
  const handleDelete = (messageReceiver: BusinessAPI.MessageReceiverVO) => {
    Dialog.open("dialog", {
      title: "删除消息",
      content: "确定要删除这条消息吗?",
      confirmText: "确定",
      cancelText: "取消",
      onConfirm: async () => {
        try {
          const { data } =
            await business.messageReceiver.destroyMessageReceiver({
              messageReceiverId: messageReceiver.messageReceiverId,
            });

          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 (
    <PageList<BusinessAPI.MessageReceiverVO, BusinessAPI.MessageReceiverPageQry>
      rowId={"messageReceiverId"}
      itemHeight={182}
      type={"infinite"}
      actionRef={actionRef}
      render={(messageReceiverVO: BusinessAPI.MessageReceiverVO, index) => {
        const { messageVO } = messageReceiverVO;
        return (
          <View className={"mb-2.5"} key={index}>
            <View
              className={classNames(
                "relative flex flex-col divide-y divide-neutral-100 overflow-hidden rounded-xl bg-white shadow-sm",
                !messageReceiverVO.isRead && "border-l-4 border-l-blue-500",
              )}
              key={index}
            >
              {/* 头部区域：标题 + 已读状态 */}
              <View className="flex items-center justify-between gap-2 px-4 py-3">
                <View className="flex min-w-0 flex-1 items-center gap-2">
                  {/* 未读指示器 */}
                  {!messageReceiverVO.isRead && (
                    <View className="h-2 w-2 rounded-full bg-blue-500" />
                  )}
                  <Text className="text-neutral-darkest truncate text-base font-semibold">
                    {messageVO?.title || "暂无标题"}
                  </Text>
                </View>
                <View className="flex flex-col items-end gap-1">
                  <Text
                    className={classNames(
                      "rounded px-2 py-0.5 text-xs font-medium",
                      messageReceiverVO.isRead
                        ? "bg-gray-100 text-gray-600"
                        : "bg-blue-100 text-blue-600",
                    )}
                  >
                    {messageReceiverVO.isRead ? "已读" : "未读"}
                  </Text>
                </View>
              </View>

              {/* 详细信息区域 */}
              <View className="flex cursor-pointer flex-col gap-2 px-4 py-3">
                <View className="flex flex-col gap-1">
                  <Text className="text-neutral-dark text-xs">消息内容</Text>
                  <Text
                    className="text-neutral-darkest text-sm break-words whitespace-pre-wrap"
                    style={{
                      whiteSpace: "pre-wrap",
                      wordBreak: "break-word",
                    }}
                  >
                    {messageVO?.content || "暂无内容"}
                  </Text>
                </View>
                <View className="flex flex-row items-center justify-between">
                  <Text className="text-neutral-dark text-xs">接收时间</Text>
                  <Text className="text-neutral-darkest text-xs font-medium">
                    {messageReceiverVO.createdAt
                      ? dayjs(messageReceiverVO.createdAt).format(
                          "YYYY-MM-DD HH:mm",
                        )
                      : "-"}
                  </Text>
                </View>
                {messageReceiverVO.readAt && (
                  <View className="flex flex-row items-center justify-between">
                    <Text className="text-neutral-dark text-xs">已读时间</Text>
                    <Text className="text-neutral-darkest text-xs font-medium">
                      {dayjs(messageReceiverVO.readAt).format(
                        "YYYY-MM-DD HH:mm",
                      )}
                    </Text>
                  </View>
                )}
              </View>

              {/* 操作按钮区域 */}
              <View className="flex justify-end gap-2 border-t border-neutral-100 bg-gray-50 px-4 py-3">
                {!messageReceiverVO.isRead && (
                  <Button
                    type="primary"
                    size="small"
                    onClick={(e) => {
                      handleMarkAsRead(messageReceiverVO);
                      e.stopPropagation();
                    }}
                  >
                    标记已读
                  </Button>
                )}
                <Button
                  type="primary"
                  size="small"
                  onClick={async (e) => {
                    e.stopPropagation();
                    if (messageVO?.subjectType === "AUDIT") {
                      const {
                        data: { data: auditVO, success },
                      } = await business.audit.showAudit({
                        auditShowQry: {
                          auditId: messageVO.subjectId,
                        },
                      });

                      if (!success || !auditVO) {
                        return;
                      }

                      if (auditVO.subjectType === "PURCHASE_ORDER") {
                        if (
                          auditVO.type === "REVIEWER_AUDIT" ||
                          (auditVO.type === "BOSS_AUDIT" &&
                            auditVO.state === "AUDIT_REJECTED")
                        ) {
                          await Taro.navigateTo({
                            url: buildUrl("/pages/audit/audit", {
                              orderId: auditVO.subjectId,
                              auditId: auditVO.auditId,
                            }),
                          });
                          return;
                        }
                        if (auditVO.type === "BOSS_AUDIT") {
                          await Taro.navigateTo({
                            url: buildUrl("/pages/approval/audit", {
                              orderId: auditVO.subjectId,
                              auditId: auditVO.auditId,
                            }),
                          });
                          return;
                        }
                      }
                    }
                  }}
                >
                  去处理
                </Button>
                <Button
                  type="danger"
                  size="small"
                  onClick={(e) => {
                    handleDelete(messageReceiverVO);
                    e.stopPropagation();
                  }}
                >
                  删除
                </Button>
              </View>
            </View>
          </View>
        );
      }}
      request={async (params) => {
        const {
          data: { data, success, notEmpty },
        } = await business.messageReceiver.pageMessageReceiver({
          messageReceiverPageQry: {
            ...params,
          },
        });

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