import { Badge, Button, ErrorBlock, List, NavBar, PullToRefresh, Tabs, Tag, Toast } from 'antd-mobile';
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { NoticeResp, noticeApi } from '@/api/notice';
import { NotificationResp, notificationApi } from '@/api/notification';

export default function NoticeList() {
  const [tab, setTab] = useState('notifications');

  return (
    <div className="page">
      <NavBar back={null}>알림 / 공지</NavBar>
      <Tabs activeKey={tab} onChange={setTab}>
        <Tabs.Tab title="내 알림" key="notifications">
          <Notifications />
        </Tabs.Tab>
        <Tabs.Tab title="공지사항" key="notices">
          <Notices />
        </Tabs.Tab>
      </Tabs>
    </div>
  );
}

function Notifications() {
  const qc = useQueryClient();
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['mobile.me.notifications'],
    queryFn: () => notificationApi.list({ pageNum: 1, pageSize: 50 }),
  });
  const items = data?.list ?? [];
  const unreadCount = items.filter((n) => !n.isRead).length;

  const onItemClick = async (n: NotificationResp) => {
    if (!n.isRead) {
      try {
        await notificationApi.markRead(n.notificationId);
        await qc.invalidateQueries({ queryKey: ['mobile.me.notifications'] });
        await qc.invalidateQueries({ queryKey: ['mobile.me.summary'] });
      } catch {
        // interceptor 가 토스트 처리
      }
    }
  };

  const onMarkAllRead = async () => {
    try {
      const affected = await notificationApi.markAllRead();
      Toast.show({ icon: 'success', content: `${affected}건 읽음 처리되었습니다` });
      await qc.invalidateQueries({ queryKey: ['mobile.me.notifications'] });
      await qc.invalidateQueries({ queryKey: ['mobile.me.summary'] });
    } catch {
      // interceptor 처리
    }
  };

  return (
    <PullToRefresh onRefresh={async () => { await refetch(); }}>
      <div style={{ paddingTop: 4 }}>
        {unreadCount > 0 && (
          <div style={{ padding: '8px 12px', textAlign: 'right' }}>
            <Button size="mini" onClick={onMarkAllRead}>모두 읽음 ({unreadCount})</Button>
          </div>
        )}
        {!isLoading && items.length === 0 && (
          <ErrorBlock status="empty" title="알림이 없습니다" />
        )}
        {items.length > 0 && (
          <List>
            {items.map((n: NotificationResp) => (
              <List.Item
                key={n.notificationId}
                onClick={() => onItemClick(n)}
                clickable
                title={
                  <span>
                    {!n.isRead && <Badge color="#ff3141" style={{ marginRight: 6 }} />}
                    {n.title}
                  </span>
                }
                description={
                  <span style={{ fontSize: 12 }}>
                    {n.refType && <Tag color="default" style={{ marginRight: 6 }}>{n.refType}</Tag>}
                    {n.content ?? ''}
                  </span>
                }
                extra={<span style={{ fontSize: 11, color: '#aaa' }}>{n.createdAt ?? ''}</span>}
              />
            ))}
          </List>
        )}
      </div>
    </PullToRefresh>
  );
}

function Notices() {
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['mobile.notices.active'],
    queryFn: () => noticeApi.active(),
  });
  const items = data ?? [];

  return (
    <PullToRefresh onRefresh={async () => { await refetch(); }}>
      <div style={{ paddingTop: 4 }}>
        {!isLoading && items.length === 0 && (
          <ErrorBlock status="empty" title="활성 공지가 없습니다" />
        )}
        {items.length > 0 && (
          <List>
            {items.map((n: NoticeResp) => (
              <List.Item
                key={n.noticeId}
                title={n.title}
                description={
                  <span style={{ fontSize: 12 }}>
                    {n.startAt ?? ''}{' '}
                    {n.noticeType && <Tag style={{ marginLeft: 6 }} color="default">{n.noticeType}</Tag>}
                  </span>
                }
              />
            ))}
          </List>
        )}
      </div>
    </PullToRefresh>
  );
}
