// ============================================================
// AnnouncementDrawer — 公告侧拉抽屉（SPA 内部弹出）
//
// 数据由父组件（NavBar）通过 useAnnouncements Hook 提供：
//   - 挂载时自动拉取 + 每 15 分钟轮询
//   - 打开抽屉时已标记已读（Badge 消除）
// ============================================================

import {useState} from 'react';
import {Drawer, Card, Typography, Empty, Tag, Spin, Modal, Tooltip} from 'antd';
import {NotificationOutlined} from '@ant-design/icons';

import type { Announcement, AnnouncementTypeValue } from '@/modules/announcement/controllers/announcement-api';
import { EnumResolver } from '@/shared/utils/enum-resolver';

const {Text, Paragraph} = Typography;

// ---------- 辅助 ----------

/** 格式化日期（YYYY-MM-DD HH:mm） */
function formatDate(iso: string): string {
    try {
        return new Date(iso).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
        });
    } catch {
        return iso;
    }
}

// ---------- 组件 ----------

interface AnnouncementDrawerProps {
    open: boolean;
    onClose: () => void;
    /** 公告列表（由 useAnnouncements Hook 提供） */
    announcements: Announcement[];
    /** 是否正在加载（由 useAnnouncements Hook 提供） */
    loading: boolean;
}

export function AnnouncementDrawer({open, onClose, announcements, loading}: AnnouncementDrawerProps) {
    // 详情 Modal
    const [detail, setDetail] = useState<Announcement | null>(null);

    // ---- 渲染 ----

    return (
        <>
            <Drawer
                title={
                    <span className="flex items-center gap-2">
                  <NotificationOutlined />
                  公告
               </span>
                }
                placement="right"
                size={380}
                open={open}
                onClose={onClose}
                styles={{body: {padding: 0}}}
            >
                {loading ? (
                    <div className="flex items-center justify-center h-64">
                        <Spin description="加载中..." />
                    </div>
                ) : announcements.length === 0 ? (
                    <div className="flex items-center justify-center h-64">
                        <Empty description="暂无公告" />
                    </div>
                ) : (
                    <div className="flex flex-col gap-3 p-3">
                        {announcements.map((item:Announcement) => (
                            <Tooltip
                                key={item.id}
                                title={
                                    item.content.length > 100
                                        ? item.content.slice(0, 200) + '…'
                                        : undefined
                                }
                                placement="left"
                            >
                                <Card
                                    size="small"
                                    className="rounded-md! border-0! shadow-sm! cursor-pointer hover:shadow-md! transition-shadow"
                                    title={
                                        <Text strong className="text-sm" ellipsis>
                                            {item.pinned && '📌 '}
                                            {item.title}
                                        </Text>
                                    }
                                    extra={
                                        <Tag
                                            color={EnumResolver.announcement.type.color(item.type as AnnouncementTypeValue)}
                                            className="m-0! text-xs"
                                        >
                                            {EnumResolver.announcement.type.label(item.type as AnnouncementTypeValue)}
                                        </Tag>
                                    }
                                    onClick={() => setDetail(item)}
                                >
                                    <Paragraph
                                        className="mb-2! text-xs"
                                        type="secondary"
                                        ellipsis={{rows: 2}}
                                    >
                                        {item.content}
                                    </Paragraph>
                                    <Text type="secondary" className="text-xs">
                                        {formatDate(item.created_at)}
                                    </Text>
                                </Card>
                            </Tooltip>
                        ))}
                    </div>
                )}
            </Drawer>

            {/* ======== 公告详情 Modal ======== */}
            <Modal
                open={!!detail}
                onCancel={() => setDetail(null)}
                footer={null}
                width={480}
                centered
                title={
                    detail && (
                        <span className="flex items-center gap-2">
                     {detail.pinned && '📌 '}
                            {detail.title}
                  </span>
                    )
                }
            >
                {detail && (
                    <div className="flex flex-col gap-3">
                        <div className="flex items-center gap-2">
                            <Tag
                                color={EnumResolver.announcement.type.color(detail.type as AnnouncementTypeValue)}
                                className="m-0! text-xs"
                            >
                                {EnumResolver.announcement.type.label(detail.type as AnnouncementTypeValue)}
                            </Tag>
                            <Text type="secondary" className="text-xs">
                                {formatDate(detail.created_at)}
                            </Text>
                        </div>
                        <div className="px-1 py-2 rounded-md"
                             style={{
                                 background: 'var(--color-fill-tertiary, rgba(0,0,0,0.04))',
                             }}
                        >
                            <Paragraph className="mb-0! text-sm leading-relaxed whitespace-pre-wrap">
                                {detail.content}
                            </Paragraph>
                        </div>
                    </div>
                )}
            </Modal>
        </>
    );
}
