import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Tag } from 'antd';
import dayjs from 'dayjs';
import { receiveApi } from '@/api/receive';
import SearchForm from '@/components/common/SearchForm';
import DataTable from '@/components/common/DataTable';

export default function ErrorList() {
  const [param, setParam] = useState<any>({ pageNum: 1, pageSize: 20 });
  const { data, isLoading } = useQuery({
    queryKey: ['receive-errors', param],
    queryFn: () => receiveApi.listErrors(param),
  });

  return (
    <div>
      <SearchForm
        conditions={[
          { type: 'text', name: 'companyCode',   label: '보험사 코드' },
          { type: 'code', name: 'errorType',     label: '에러 유형',  groupCode: 'ERROR_TYPE' },
          { type: 'code', name: 'resolveStatus', label: '처리 상태', groupCode: 'RESOLVE_STATUS' },
        ]}
        onSearch={(v) => setParam({ ...param, ...v, pageNum: 1 })}
      />
      <DataTable
        data={data as any}
        page={{ pageNum: param.pageNum, pageSize: param.pageSize }}
        onPageChange={(p) => setParam({ ...param, ...p })}
        loading={isLoading}
        columns={[
          { title: '보험사', dataIndex: 'companyName' },
          { title: '에러 유형', dataIndex: 'errorTypeName',
            render: (v: string) => <Tag color="red">{v}</Tag> },
          { title: '필드',  dataIndex: 'errorField' },
          { title: '값',    dataIndex: 'errorValue', ellipsis: true },
          { title: '메시지', dataIndex: 'errorMessage', ellipsis: true },
          { title: '처리상태', dataIndex: 'resolveStatusName',
            render: (v: string, r: any) => v === '처리완료'
              ? <Tag color="green">{v}</Tag>
              : <Tag color="orange">{v}</Tag> },
          { title: '발생시각', dataIndex: 'createdAt',
            render: (v: string) => v && dayjs(v).format('YYYY-MM-DD HH:mm') },
        ]}
      />
    </div>
  );
}
