import { useState } from 'react';
import { Alert, Card, Col, Form, Input, InputNumber, Row, Statistic, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ColDef } from '@ag-grid-community/core';
import PageContainer from '@/components/common/PageContainer';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import { operationApi, SimulationRow, SimulationRequest } from '@/api/operation';
import { GRAY, RADIUS, SHADOW, COLOR_PRIMARY, COLOR_ERROR, COLOR_SUCCESS } from '@/theme/tokens';

const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';
const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

const HIST_COLS: ColDef<SimulationRow>[] = [
  { field: 'simName',            headerName: '시나리오명', width: 150 },
  { field: 'premiumAmount',      headerName: '보험료',    width: 130, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'companyRate',        headerName: '보험사요율(%)', width: 130, type: 'numericColumn',
    valueFormatter: (p) => `${((p.value as number) * 100).toFixed(2)}%` },
  { field: 'payoutRate',         headerName: '지급률(%)', width: 110, type: 'numericColumn',
    valueFormatter: (p) => `${((p.value as number) * 100).toFixed(2)}%` },
  { field: 'commissionYear',     headerName: '회차',     width: 70, type: 'numericColumn' },
  { field: 'companyPayment',     headerName: '보험사지급액', width: 140, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'agentCommission',    headerName: '설계사수수료', width: 140, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'withholdingTax',     headerName: '원천세(3.3%)', width: 130, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'netAmount',          headerName: '실지급',   width: 120, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'expectedChargeback', headerName: '예상환수', width: 120, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'createdAt',          headerName: '계산일시', flex: 1 },
];

export default function CommissionSimulator() {
  const qc = useQueryClient();
  const [form] = Form.useForm();
  const [result, setResult] = useState<SimulationRow | null>(null);

  const { data: listData, isLoading, isError } = useQuery({
    queryKey: ['commission-simulation', 'list'],
    queryFn: () => operationApi.simulationList(),
    retry: false,
  });

  const rows = listData?.list ?? [];

  const handleSimulate = async () => {
    const values = await form.validateFields();
    // UI: 율은 % 단위 → 백엔드는 0~1
    const body: SimulationRequest = {
      simName:       values.simName as string,
      premiumAmount: values.premiumAmount as number,
      companyRate:   (values.companyRate as number) / 100,
      payoutRate:    (values.payoutRate as number) / 100,
      commissionYear: values.commissionYear as number,
    };
    try {
      const res = await operationApi.simulate(body);
      setResult(res);
      message.success('계산 완료');
      qc.invalidateQueries({ queryKey: ['commission-simulation', 'list'] });
    } catch { /* request.ts 처리 */ }
  };

  return (
    <PageContainer title="수수료 시뮬레이터" description="보험료/요율/지급률 입력 후 수수료 계산">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/commission-simulations 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      {/* 입력 폼 */}
      <ProCard title="시뮬레이션 입력" style={{ ...cardStyle, marginBottom: 16 }}>
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="simName" label="시나리오명" rules={[{ required: true }]}>
                <Input placeholder="시나리오명" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="premiumAmount" label="보험료(원)" rules={[{ required: true }]}>
                <InputNumber style={{ width: '100%' }} min={0} />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="companyRate" label="보험사요율(%)" rules={[{ required: true }]}>
                <InputNumber style={{ width: '100%' }} min={0} max={100} step={0.01} addonAfter="%" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="payoutRate" label="지급률(%)" rules={[{ required: true }]}>
                <InputNumber style={{ width: '100%' }} min={0} max={100} step={0.01} addonAfter="%" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="commissionYear" label="회차" rules={[{ required: true }]}>
                <InputNumber style={{ width: '100%' }} min={1} />
              </Form.Item>
            </Col>
          </Row>
          <PermissionButton menuCode="COMM_SIMULATOR" permCode="CREATE" type="primary" onClick={handleSimulate}>
            계산
          </PermissionButton>
        </Form>
      </ProCard>

      {/* 결과 카드 */}
      {result && (
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={4}>
            <Card style={cardStyle}>
              <Statistic title="보험사지급액" value={result.companyPayment} formatter={(v) => (v as number).toLocaleString()} suffix="원" valueStyle={{ color: COLOR_PRIMARY }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card style={cardStyle}>
              <Statistic title="설계사수수료" value={result.agentCommission} formatter={(v) => (v as number).toLocaleString()} suffix="원" valueStyle={{ color: COLOR_PRIMARY }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card style={cardStyle}>
              <Statistic title="원천세(3.3%)" value={result.withholdingTax} formatter={(v) => (v as number).toLocaleString()} suffix="원" valueStyle={{ color: COLOR_ERROR }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card style={cardStyle}>
              <Statistic title="실지급" value={result.netAmount} formatter={(v) => (v as number).toLocaleString()} suffix="원" valueStyle={{ color: COLOR_SUCCESS }} />
            </Card>
          </Col>
          <Col span={4}>
            <Card style={cardStyle}>
              <Statistic title="예상환수" value={result.expectedChargeback ?? 0} formatter={(v) => (v as number).toLocaleString()} suffix="원" valueStyle={{ color: COLOR_ERROR }} />
            </Card>
          </Col>
        </Row>
      )}

      {/* 저장된 시뮬 목록 */}
      <ProCard title="저장된 시뮬레이션 목록" style={cardStyle}>
        <DataGrid<SimulationRow>
          rows={rows}
          columns={HIST_COLS}
          loading={isLoading}
          height={400}
          rowKey="simId"
        />
      </ProCard>
    </PageContainer>
  );
}
