import { ProTable, type ProColumns } from '@ant-design/pro-components';
import { Tag } from 'antd';
import PageContainer from '@/components/common/PageContainer';
import { useCommonCodes } from '@/hooks/useCommonCodes';
import { receiveApi, RawCommissionResp, ParseErrorResp } from '@/api/receive';

const STATUS_COLOR = { PENDING: 'processing', OK: 'success', ERROR: 'error' } as const;

export default function ReceiveData() {
  const { data: companies = [] } = useCommonCodes('COMPANY_CODE');

  const rawColumns: ProColumns<RawCommissionResp>[] = [
    {
      title: '보험사', dataIndex: 'companyCode', width: 110, valueType: 'select',
      valueEnum: Object.fromEntries(companies.map((c) => [c.code, { text: c.codeName }])),
    },
    { title: '정산월', dataIndex: 'settleMonth', width: 90, valueType: 'dateMonth',
      fieldProps: { format: 'YYYYMM' } },
    {
      title: '파싱상태', dataIndex: 'parseStatus', width: 110, valueType: 'select',
      valueEnum: { PENDING: { text: '대기' }, OK: { text: '성공' }, ERROR: { text: '실패' } },
      render: (_, r) => <Tag color={STATUS_COLOR[r.parseStatus as 'PENDING' | 'OK' | 'ERROR'] ?? 'default'}>
        {r.parseStatus}</Tag>,
    },
    { title: '데이터 유형', dataIndex: 'dataType', width: 110, search: false },
    { title: '배치 ID', dataIndex: 'batchId', width: 140, search: false },
    { title: '파일명', dataIndex: 'fileName', width: 200, search: false, ellipsis: true },
    { title: '행 번호', dataIndex: 'rowNumber', width: 80, align: 'right', search: false },
    { title: '연결 원장', dataIndex: 'mappedLedgerId', width: 100, align: 'right', search: false },
    { title: '수신일시', dataIndex: 'receivedAt', width: 160, search: false },
    { title: '파싱일시', dataIndex: 'parsedAt', width: 160, search: false },
  ];

  return (
    <PageContainer title="수신 데이터" description="보험사 수수료 raw 데이터 / 파싱 상태">
      <ProTable<RawCommissionResp>
        rowKey="rawId"
        columns={rawColumns}
        scroll={{ x: 1300 }}
        request={async (params) => {
          const list = await receiveApi.raw({
            companyCode: (params as any).companyCode,
            settleMonth: (params as any).settleMonth,
            parseStatus: (params as any).parseStatus,
          });
          return { data: list, total: list.length, success: true };
        }}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
        search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        dateFormatter="string"
      />
    </PageContainer>
  );
}
