import { Card, List, NavBar, Space, Tag } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useAuthStore } from '@/stores/authStore';
import { notificationApi } from '@/api/notification';

export default function Home() {
  const navigate = useNavigate();
  const profile = useAuthStore((s) => s.profile);
  const clear = useAuthStore((s) => s.clear);

  const summary = useQuery({
    queryKey: ['mobile.me.summary'],
    queryFn: () => notificationApi.summary(),
    staleTime: 10_000,
  });

  const s = summary.data;
  const loading = summary.isLoading;

  return (
    <div className="page">
      <NavBar back={null} right={<a onClick={() => { clear(); navigate('/login'); }} style={{ fontSize: 14 }}>로그아웃</a>}>
        홈
      </NavBar>
      <div style={{ padding: 16 }}>
        <Card>
          <div style={{ fontSize: 18, fontWeight: 700 }}>
            {profile?.userName ?? profile?.loginId ?? '사용자'} 님
          </div>
          <div style={{ color: '#888', fontSize: 13, marginTop: 4 }}>
            {profile?.agentName ? `${profile.agentName} · ${profile.orgName ?? ''}` : '설계사 정보 없음'}
          </div>
          {profile?.roleCodes && profile.roleCodes.length > 0 && (
            <div style={{ marginTop: 8 }}>
              <Space wrap>
                {profile.roleCodes.map((r) => <Tag key={r} color="primary">{r}</Tag>)}
              </Space>
            </div>
          )}
        </Card>

        <div style={{ marginTop: 16 }}>
          <List header="요약">
            <List.Item
              extra={loading ? '...' : `총 ${s?.statementCount ?? 0}건`}
              onClick={() => navigate('/statement')}
              clickable
            >
              정산 명세서
            </List.Item>
            <List.Item
              extra={loading ? '...' : `총 ${s?.withdrawRequestCount ?? 0}건`}
              onClick={() => navigate('/withdraw')}
              clickable
            >
              출금 신청
            </List.Item>
            <List.Item
              extra={
                loading
                  ? '...'
                  : (s?.unreadNotificationCount ?? 0) > 0
                  ? <Tag color="danger">{s?.unreadNotificationCount}건 안 읽음</Tag>
                  : '모두 확인'
              }
              onClick={() => navigate('/notice')}
              clickable
            >
              알림 / 공지
            </List.Item>
          </List>
        </div>

        {s && !s.agentId && (
          <div style={{ marginTop: 24, fontSize: 12, color: '#f96', textAlign: 'center' }}>
            본 계정에 연결된 설계사(agent)가 없습니다. 명세서·출금 조회가 제한됩니다.
          </div>
        )}
      </div>
    </div>
  );
}
