import { Button, Dialog, ErrorBlock, List, NavBar, PullToRefresh, SwipeAction, Tag, Toast } from 'antd-mobile';
import { AddOutline } from 'antd-mobile-icons';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
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 navigate = useNavigate();
  const { data, isLoading, refetch, error } = useQuery({
    queryKey: ['mobile.me.withdraws'],
    queryFn: () => withdrawApi.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}
        right={
          !forbidden && (
            <Button size="mini" color="primary" onClick={() => navigate('/withdraw/new')}>
              <AddOutline /> 신청
            </Button>
          )
        }
      >
        출금 신청
      </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="출금 신청 내역이 없습니다" />
          )}
          {items.length > 0 && (
            <List>
              {items.map((w: WithdrawResp) => {
                const cancellable = w.status === 'REQUESTED';
                const row = (
                  <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>}
                  />
                );
                if (!cancellable) return row;
                return (
                  <SwipeAction
                    key={w.requestId}
                    rightActions={[{
                      key: 'cancel', text: '취소', color: 'danger',
                      onClick: async () => {
                        const ok = await Dialog.confirm({ content: `#${w.requestId} 출금 신청을 취소하시겠습니까?` });
                        if (!ok) return;
                        await withdrawApi.cancel(w.requestId);
                        Toast.show({ icon: 'success', content: '취소되었습니다' });
                        await refetch();
                      },
                    }]}
                  >
                    {row}
                  </SwipeAction>
                );
              })}
            </List>
          )}
        </div>
      </PullToRefresh>
    </div>
  );
}
