import { ErrorBlock, List, NavBar, PullToRefresh, Tag } from 'antd-mobile';
import { useQuery } from '@tanstack/react-query';
import { useAuthStore } from '@/stores/authStore';
import { WithdrawResp, withdrawApi } from '@/api/withdraw';

const STATUS_COLOR: Record<string, string> = {
  REQUESTED: 'default',
  APPROVED: 'primary',
  SENT: 'success',
  COMPLETED: 'success',
  FAILED: 'danger',
  CANCELLED: 'default',
};

export default function WithdrawList() {
  const agentId = useAuthStore((s) => s.profile?.agentId);
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['withdraws', agentId],
    enabled: !!agentId,
    queryFn: () => withdrawApi.list({ agentId, pageNum: 1, pageSize: 50 }),
  });

  const items = data?.list ?? [];

  return (
    <div className="page">
      <NavBar back={null}>출금 신청</NavBar>
      <PullToRefresh onRefresh={async () => { await refetch(); }}>
        <div style={{ padding: 0, paddingTop: 8 }}>
          {!agentId && (
            <ErrorBlock status="empty" title="설계사 미연결" description="본 계정에는 설계사가 연결되어 있지 않습니다." />
          )}
          {agentId && !isLoading && items.length === 0 && (
            <ErrorBlock status="empty" title="출금 신청 내역이 없습니다" />
          )}
          {items.length > 0 && (
            <List>
              {items.map((w: WithdrawResp) => (
                <List.Item
                  key={w.requestId}
                  title={
                    <span>
                      #{w.requestId} {w.settleMonth ?? ''}
                    </span>
                  }
                  description={
                    <span style={{ fontSize: 12 }}>
                      {w.bankCode ?? '-'} · {w.accountNo ?? '-'} · {w.amount.toLocaleString()}원
                      {w.transferTxId && <> · txId={w.transferTxId}</>}
                    </span>
                  }
                  extra={<Tag color={STATUS_COLOR[w.status] ?? 'default'}>{w.statusName ?? w.status}</Tag>}
                />
              ))}
            </List>
          )}
        </div>
      </PullToRefresh>
    </div>
  );
}
