import { useState } from 'react';
import { Alert, Col, Empty, Row, Spin } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
} from 'recharts';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import ExcelExportButton from '@/components/common/ExcelExportButton';
import api, { unwrap } from '@/api/request';

interface PerfRow {
  settleMonth: string;
  agentCount: number;
  recruitTotal: number;
  maintainTotal: number;
  netAmount: number;
}

function fetchPerf(year: string) {
  return unwrap<PerfRow[]>(api.get('/api/report/performance', { params: { year } }));
}

export default function PerformanceReport() {
  const [year] = useState(() => dayjs().format('YYYY'));

  const { data, isLoading, isError } = useQuery({
    queryKey: ['report', 'performance', year],
    queryFn: () => fetchPerf(year),
    retry: false,
  });

  return (
    <PageContainer
      title="실적 리포트"
      description="월별 수수료 집계 — 모집/유지/실지급"
      extra={<ExcelExportButton url="/api/report/performance/export" fileName="실적리포트" params={{ year }} />}
    >
      {isError && (
        <Alert
          type="warning"
          showIcon
          message="백엔드 미구현 — 곧 추가됩니다"
          description="/api/report/performance API가 아직 준비되지 않았습니다."
          style={{ marginBottom: 16 }}
        />
      )}

      <ProCard bordered style={{ marginBottom: 16 }}>
        <Spin spinning={isLoading}>
          {data && data.length > 0 ? (
            <ResponsiveContainer width="100%" height={340}>
              <BarChart data={data} margin={{ top: 16, right: 24, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="settleMonth" />
                <YAxis tickFormatter={(v: number | string) => `${(Number(v) / 1_000_000).toFixed(0)}백만`} />
                <Tooltip formatter={(v: number | string) => Number(v).toLocaleString()} />
                <Legend />
                <Bar dataKey="recruitTotal" name="모집수수료" fill="#1677ff" />
                <Bar dataKey="maintainTotal" name="유지수수료" fill="#52c41a" />
                <Bar dataKey="netAmount" name="실지급" fill="#faad14" />
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <Empty description={isLoading ? '로딩 중...' : '데이터 없음'} style={{ padding: 40 }} />
          )}
        </Spin>
      </ProCard>

      {data && data.length > 0 && (
        <ProCard bordered>
          <Row gutter={16}>
            {data.map((row) => (
              <Col key={row.settleMonth} xs={24} sm={12} md={8} lg={6} xl={4}>
                <ProCard size="small" bordered style={{ marginBottom: 8 }}>
                  <div style={{ fontWeight: 600, marginBottom: 4 }}>{row.settleMonth}</div>
                  <div style={{ fontSize: 12, color: '#666' }}>설계사: {row.agentCount}명</div>
                  <div style={{ fontSize: 12, color: '#1677ff' }}>
                    모집: {(row.recruitTotal ?? 0).toLocaleString()}
                  </div>
                  <div style={{ fontSize: 12, color: '#52c41a' }}>
                    유지: {(row.maintainTotal ?? 0).toLocaleString()}
                  </div>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>
                    실지급: {(row.netAmount ?? 0).toLocaleString()}
                  </div>
                </ProCard>
              </Col>
            ))}
          </Row>
        </ProCard>
      )}
    </PageContainer>
  );
}
