import { Alert } from 'antd';
import { ProTable, type ProColumns } from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import PageContainer from '@/components/common/PageContainer';
import MoneyText from '@/components/common/MoneyText';
import ExcelExportButton from '@/components/common/ExcelExportButton';
import api, { unwrap } from '@/api/request';

interface RiskRow {
  agentId: number;
  agentName: string;
  orgName: string;
  policyNo: string;
  companyName: string;
  recruitMonth: string;
  monthsElapsed: number;
  recruitAmount: number;
  chargebackRate: number;
  estimatedChargeback: number;
  riskLevel: 'HIGH' | 'MEDIUM' | 'LOW';
}

function fetchRisk() {
  return unwrap<RiskRow[]>(api.get('/api/report/chargeback-risk'));
}

const riskColor: Record<string, string> = {
  HIGH: '#f5222d',
  MEDIUM: '#fa8c16',
  LOW: '#52c41a',
};

const riskLabel: Record<string, string> = {
  HIGH: '고위험',
  MEDIUM: '중위험',
  LOW: '저위험',
};

const columns: ProColumns<RiskRow>[] = [
  { title: '설계사', dataIndex: 'agentName', width: 100, fixed: 'left' },
  { title: '소속', dataIndex: 'orgName', width: 160 },
  { title: '증권번호', dataIndex: 'policyNo', width: 130 },
  { title: '보험사', dataIndex: 'companyName', width: 110 },
  { title: '모집월', dataIndex: 'recruitMonth', width: 90 },
  { title: '경과월', dataIndex: 'monthsElapsed', width: 80, align: 'right', render: (_, r) => `${r.monthsElapsed}개월` },
  {
    title: '모집수수료', dataIndex: 'recruitAmount', width: 120, align: 'right',
    render: (_, r) => <MoneyText value={r.recruitAmount} />,
  },
  {
    title: '환수율(%)', dataIndex: 'chargebackRate', width: 90, align: 'right',
    render: (_, r) => `${r.chargebackRate}%`,
  },
  {
    title: '예상환수액', dataIndex: 'estimatedChargeback', width: 130, align: 'right',
    render: (_, r) => <MoneyText value={r.estimatedChargeback} />,
  },
  {
    title: '위험등급', dataIndex: 'riskLevel', width: 90, align: 'center', fixed: 'right',
    render: (_, r) => (
      <span style={{ color: riskColor[r.riskLevel], fontWeight: 600 }}>
        {riskLabel[r.riskLevel] ?? r.riskLevel}
      </span>
    ),
  },
];

export default function ChargebackRiskReport() {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['report', 'chargeback-risk'],
    queryFn: fetchRisk,
    retry: false,
  });

  return (
    <PageContainer
      title="환수위험 리포트"
      description="경과월별 환수 가능성 분석"
      extra={<ExcelExportButton url="/api/report/chargeback-risk/export" fileName="환수위험리포트" />}
    >
      {isError && (
        <Alert
          type="warning"
          showIcon
          message="백엔드 미구현 — 곧 추가됩니다"
          description="/api/report/chargeback-risk API가 아직 준비되지 않았습니다."
          style={{ marginBottom: 16 }}
        />
      )}

      <ProTable<RiskRow>
        rowKey={(r) => `${r.agentId}-${r.policyNo}`}
        columns={columns}
        dataSource={data ?? []}
        loading={isLoading}
        search={false}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t}건` }}
        options={{ density: false, reload: false }}
        scroll={{ x: 1100 }}
      />
    </PageContainer>
  );
}
