// ============================================================
// AnnouncementDrawer — 公告侧拉抽屉（SPA 内部弹出）
// 数据来源：GET /api/v1/announcements
// ============================================================

import { useEffect, useState, useCallback } from 'react';
import { Drawer, List, Typography, Empty, Tag, Spin } from 'antd';
import { NotificationOutlined } from '@ant-design/icons';

import { fetchAnnouncements, type Announcement } from '@/services/modules';

const { Text, Paragraph } = Typography;

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

/** 公告类型 → Tag 颜色映射 */
const typeColorMap: Record<string, string> = {
   system: 'blue',
   feature: 'purple',
   activity: 'orange',
   maintenance: 'red',
};

/** 公告类型 → 中文标签 */
const typeLabelMap: Record<string, string> = {
   system: '系统',
   feature: '功能',
   activity: '活动',
   maintenance: '维护',
};

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

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

interface AnnouncementDrawerProps {
   open: boolean;
   onClose: () => void;
}

export function AnnouncementDrawer({ open, onClose }: AnnouncementDrawerProps) {
   const [list, setList] = useState<Announcement[]>([]);
   const [loading, setLoading] = useState(false);
   const [error, setError] = useState<string | null>(null);

   // 打开抽屉时请求公告列表
   const loadAnnouncements = useCallback(async () => {
      setLoading(true);
      setError(null);
      try {
         const data = await fetchAnnouncements();
         // 仅展示有效公告
         setList(data.filter((item) => item.is_active));
      } catch (err) {
         setError((err as Error).message || '加载公告失败');
         setList([]);
      } finally {
         setLoading(false);
      }
   }, []);

   useEffect(() => {
      if (open) {
         loadAnnouncements();
      }
   }, [open, loadAnnouncements]);

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

   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>
         ) : error ? (
            <div className="flex items-center justify-center h-64">
               <Empty description={error} />
            </div>
         ) : list.length === 0 ? (
            <div className="flex items-center justify-center h-64">
               <Empty description="暂无公告" />
            </div>
         ) : (
            <List
               dataSource={list}
               renderItem={(item) => (
                  <List.Item className="px-6! py-4!">
                     <div className="w-full space-y-2">
                        {/* 标题 + 类型标签 */}
                        <div className="flex items-center justify-between gap-2">
                           <Text strong className="text-sm flex-1" ellipsis>
                              {item.pinned && '📌 '}
                              {item.title}
                           </Text>
                           <Tag
                              color={typeColorMap[item.type] || 'default'}
                              className="m-0! text-xs shrink-0"
                           >
                              {typeLabelMap[item.type] || item.type}
                           </Tag>
                        </div>

                        {/* 内容 */}
                        <Paragraph
                           className="mb-0! text-xs"
                           type="secondary"
                           ellipsis={{ rows: 2 }}
                        >
                           {item.content}
                        </Paragraph>

                        {/* 日期 */}
                        <Text type="secondary" className="text-xs">
                           {formatDate(item.created_at)}
                        </Text>
                     </div>
                  </List.Item>
               )}
            />
         )}
      </Drawer>
   );
}
