import React, { useState } from "react";
import { Modal, Button, Tabs, Empty, message } from "antd";
import type { TabsProps } from "antd";
import axios from "axios";
import { MESSAGE_STATUS, MESSAGE_TAB } from "@/constants";
import { useNotificationStore } from "@/store/NotificationStore";
import { Eraser, FileText } from "lucide-react";
import dayjs from "dayjs";
import { renderNoticeLength } from "@/utils/utils";

interface MessageModalProps {
  visible: boolean;
  onClose: () => void;
  socket: any;
}

const MessageModal: React.FC<MessageModalProps> = ({
  visible,
  onClose,
  socket,
}) => {
  const [activeKey, setActiveKey] = useState(MESSAGE_TAB.UNREAD);
  const { notifications, changeNotification } = useNotificationStore();
  const unreadNotifications = notifications.filter(
    (notification) => notification.is_read === MESSAGE_STATUS.UNREAD
  );

  const tabItems: TabsProps["items"] = [
    {
      key: MESSAGE_TAB.ALL,
      label: <span className="flex">全部</span>,
    },
    {
      key: MESSAGE_TAB.UNREAD,
      label: (
        <span className="flex">
          未读
          {!!unreadNotifications.length && (
            <span className="ml-1 text-xs text-white bg-red-500 rounded-full w-5 h-5 flex justify-center items-center">
              {renderNoticeLength(unreadNotifications)}
            </span>
          )}
        </span>
      ),
    },
    {
      key: MESSAGE_TAB.HAS_READ,
      label: <span className="flex">已读</span>,
    },
  ];

  return (
    <Modal
      title={
        <div className="flex items-center">
          <span>
            消息中心
            {!!renderNoticeLength(unreadNotifications) &&
              `(${renderNoticeLength(unreadNotifications)})`}
          </span>
          <div
            className="cursor-pointer hover:bg-gray-100 rounded-md px-2 py-1 ml-2 text-xs flex justify-center items-center gap-1"
            onClick={async () => {
              const res = await axios.post(`/notification/bazb/clearMsg`);
              if (res.data.code === 200) {
                changeNotification({ type: "clear" });
              }
            }}
          >
            <Eraser size={12} />
            清除消息
          </div>
        </div>
      }
      open={visible}
      onCancel={onClose}
      footer={null}
      style={{
        top: 30,
        maxWidth: "90%",
        maxHeight: "80%",
      }}
    >
      <div className="flex flex-col h-[80vh]">
        <Tabs
          activeKey={activeKey}
          items={tabItems}
          className="mb-4"
          onChange={(key) => {
            setActiveKey(key);
          }}
        />
        <div className="space-y-4 max-h-[100%] overflow-auto">
          {(() => {
            let filteredNotifications = notifications;

            if (activeKey === MESSAGE_TAB.UNREAD) {
              filteredNotifications = notifications.filter(
                (notification) => notification.is_read === MESSAGE_STATUS.UNREAD
              );
            } else if (activeKey === MESSAGE_TAB.HAS_READ) {
              filteredNotifications = notifications.filter(
                (notification) =>
                  notification.is_read === MESSAGE_STATUS.HAS_READ
              );
            }

            return (
              <>
                {filteredNotifications.length === 0 && (
                  <div className="flex justify-center items-center h-full">
                    <Empty description="暂无消息" />
                  </div>
                )}
                {filteredNotifications.map((message, index) => (
                  <div
                    key={index}
                    className="p-4 bg-gray-50 rounded-lg shadow-sm flex flex-col gap-4"
                  >
                    <div className="flex justify-between items-center">
                      <div className="flex gap-1 items-center">
                        <div className="p-1 bg-blue-500 rounded-full w-6 h-6 text-white flex justify-center items-center">
                          <FileText size={14} />
                        </div>
                        <div className="font-bold">病例时效提醒</div>
                      </div>
                      <div className="text-gray-500 text-xs">
                        {dayjs(message.timestamp).format("YYYY-MM-DD HH:mm")}
                      </div>
                    </div>
                    <div className="flex items-start space-x-4">
                      <div className="flex-1">
                        <div className="flex">
                          <h4 className="text-sm font-semibold">
                            {message.title}
                          </h4>
                        </div>
                        <p className="text-gray-700 mt-1 indent-[1.75rem]">
                          {message.content}
                        </p>
                        <p className="text-gray-700 mt-1 indent-[1.75rem]">
                          {message.footer || "祝您工作顺利！"}
                        </p>
                        <div className="mt-2 flex space-x-2 justify-end">
                          <Button
                            type="primary"
                            size="middle"
                            onClick={() => {
                              axios.post("/notification/bazb/clearMsg", {
                                msgId: message.id,
                              });
                              changeNotification({
                                type: "clear",
                                notification: [message.id],
                              });
                            }}
                          >
                            知道了
                          </Button>
                          <Button size="middle">去查看</Button>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </>
            );
          })()}
        </div>
      </div>
    </Modal>
  );
};

export default MessageModal;
