import { ErrorBlock, List, NavBar, PullToRefresh, Tag } from 'antd-mobile';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { StatementResp, statementApi } from '@/api/statement';

export default function StatementList() {
  const navigate = useNavigate();
  const { data, isLoading, refetch, error } = useQuery({
    queryKey: ['mobile.me.statements'],
    queryFn: () => statementApi.list({ pageNum: 1, pageSize: 50 }),
    retry: false,
  });

  const items = data?.list ?? [];
  const forbidden = (error as { code?: string } | undefined)?.code === 'E403';

  return (
    <div className="page">
      <NavBar back={null}>정산 명세서</NavBar>
      <PullToRefresh onRefresh={async () => { await refetch(); }}>
        <div style={{ paddingTop: 8 }}>
          {forbidden && (
            <ErrorBlock status="empty" title="설계사 미연결" description="본 계정에는 설계사가 연결되어 있지 않습니다." />
          )}
          {!forbidden && !isLoading && items.length === 0 && (
            <ErrorBlock status="empty" title="명세서가 없습니다" description="발급된 정산 명세서가 아직 없습니다." />
          )}
          {items.length > 0 && (
            <List>
              {items.map((s: StatementResp) => (
                <List.Item
                  key={s.statementId}
                  clickable
                  onClick={() => navigate(`/statement/${s.statementId}`)}
                  title={
                    <span>
                      {s.settleMonth ?? '-'}{' '}
                      <Tag color="default" style={{ marginLeft: 6 }}>{s.statementTypeName ?? s.statementType}</Tag>
                    </span>
                  }
                  description={
                    <span style={{ fontSize: 12 }}>
                      총수수료 {fmt(s.totalCommission)} · 원천세 {fmt(s.totalTax)} · 실수령 {fmt(s.netAmount)}
                    </span>
                  }
                  extra={<Tag color={s.issueStatus === 'ISSUED' ? 'success' : 'warning'}>{s.issueStatusName ?? s.issueStatus ?? '-'}</Tag>}
                />
              ))}
            </List>
          )}
        </div>
      </PullToRefresh>
    </div>
  );
}

function fmt(n?: number) {
  if (n == null) return '-';
  return n.toLocaleString();
}
