import { useState } from 'react';
import { Empty, Tag } from 'antd';
import { useQuery } from '@tanstack/react-query';
import { ProCard, ProTable, type ProColumns } from '@ant-design/pro-components';
import PageContainer from '@/components/common/PageContainer';
import { receiveApi, CompanyProfileResp, FieldMappingResp } from '@/api/receive';

export default function ReceiveMapping() {
  const [selected, setSelected] = useState<string | undefined>();

  const { data: profiles = [] } = useQuery({
    queryKey: ['receive', 'profiles'],
    queryFn: receiveApi.profiles,
  });

  const profileColumns: ProColumns<CompanyProfileResp>[] = [
    { title: '보험사', dataIndex: 'companyCode', width: 90,
      render: (_, r) => <strong>{r.companyCode}</strong> },
    { title: '데이터 형식', dataIndex: 'dataFormat', width: 110 },
    { title: '수신방법', dataIndex: 'receiveMethod', width: 110 },
    {
      title: '활성', dataIndex: 'isActive', width: 70, align: 'center',
      render: (_, r) => <Tag color={r.isActive === 'Y' ? 'success' : 'default'}>
        {r.isActive === 'Y' ? 'Y' : 'N'}</Tag>,
    },
  ];

  const fieldColumns: ProColumns<FieldMappingResp>[] = [
    { title: '#', dataIndex: 'sortOrder', width: 50, align: 'center' },
    { title: 'Source 필드', dataIndex: 'sourceField', width: 130 },
    { title: 'Source 컬럼', dataIndex: 'sourceColIndex', width: 90, align: 'right' },
    { title: 'Target 테이블', dataIndex: 'targetTable', width: 120 },
    { title: 'Target 필드', dataIndex: 'targetField', width: 130 },
    { title: 'Type', dataIndex: 'dataType', width: 100 },
    { title: '변환규칙', dataIndex: 'transformRule', width: 110,
      render: (_, r) => r.transformRule ? <Tag color="blue">{r.transformRule}</Tag> : '-' },
    { title: '기본값', dataIndex: 'defaultValue', width: 110 },
    { title: '필수', dataIndex: 'isRequired', width: 70, align: 'center',
      render: (_, r) => r.isRequired === 'Y' ? <Tag color="error">필수</Tag> : '' },
    { title: '버전', dataIndex: 'version', width: 60, align: 'center' },
  ];

  return (
    <PageContainer title="매핑 관리" description="보험사 raw 데이터 → 표준 원장 매핑 규칙">
      <ProCard split="vertical" ghost>
        <ProCard colSpan="380px" bordered title={<span style={{ fontWeight: 600 }}>보험사 프로파일</span>}>
          <ProTable<CompanyProfileResp>
            rowKey="companyCode"
            columns={profileColumns}
            dataSource={profiles}
            search={false}
            options={false}
            pagination={false}
            size="small"
            onRow={(r) => ({
              onClick: () => setSelected(r.companyCode),
              style: {
                cursor: 'pointer',
                background: selected === r.companyCode ? '#E6F1FB' : undefined,
              },
            })}
          />
        </ProCard>
        <ProCard
          ghost
          title={selected ? <span style={{ fontWeight: 600 }}>필드 매핑 — {selected}</span>
                          : <span>좌측에서 보험사 선택</span>}
        >
          {selected ? (
            <ProTable<FieldMappingResp>
              rowKey="mappingId"
              columns={fieldColumns}
              search={false}
              options={false}
              pagination={false}
              size="small"
              request={async () => {
                const list = await receiveApi.fields(selected);
                return { data: list, total: list.length, success: true };
              }}
            />
          ) : (
            <Empty description="좌측에서 보험사를 선택하세요" />
          )}
        </ProCard>
      </ProCard>
    </PageContainer>
  );
}
