import { useState } from 'react';
import { Alert, DatePicker } from 'antd';
import { ProCard, ProTable, type ProColumns } from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import dayjs, { type Dayjs } from 'dayjs';
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 OrgRow {
  orgId: number;
  orgName: string;
  orgType: string;
  agentCount: number;
  recruitTotal: number;
  maintainTotal: number;
  netAmount: number;
}

function fetchOrgReport(settleMonth: string) {
  return unwrap<OrgRow[]>(api.get('/api/report/org', { params: { settleMonth } }));
}

const columns: ProColumns<OrgRow>[] = [
  { title: '조직명', dataIndex: 'orgName', width: 180, fixed: 'left' },
  { title: '유형', dataIndex: 'orgType', width: 80 },
  { title: '설계사 수', dataIndex: 'agentCount', width: 90, align: 'right' },
  {
    title: '모집수수료', dataIndex: 'recruitTotal', width: 130, align: 'right',
    render: (_, r) => <MoneyText value={r.recruitTotal} />,
  },
  {
    title: '유지수수료', dataIndex: 'maintainTotal', width: 130, align: 'right',
    render: (_, r) => <MoneyText value={r.maintainTotal} />,
  },
  {
    title: '실지급 합계', dataIndex: 'netAmount', width: 140, align: 'right',
    render: (_, r) => <strong><MoneyText value={r.netAmount} /></strong>,
  },
];

export default function OrgReport() {
  const [settleMonth, setSettleMonth] = useState<Dayjs>(dayjs());

  const monthStr = settleMonth.format('YYYYMM');

  const { data, isLoading, isError } = useQuery({
    queryKey: ['report', 'org', monthStr],
    queryFn: () => fetchOrgReport(monthStr),
    retry: false,
  });

  return (
    <PageContainer
      title="조직별 리포트"
      description="조직 단위 정산 집계"
      extra={
        <ExcelExportButton
          url="/api/report/org/export"
          fileName="조직별리포트"
          params={{ settleMonth: monthStr }}
        />
      }
    >
      {isError && (
        <Alert
          type="warning"
          showIcon
          message="백엔드 미구현 — 곧 추가됩니다"
          description="/api/report/org API가 아직 준비되지 않았습니다."
          style={{ marginBottom: 16 }}
        />
      )}

      <ProCard bordered style={{ marginBottom: 16 }}>
        <DatePicker
          picker="month"
          value={settleMonth}
          onChange={(d) => d && setSettleMonth(d)}
          allowClear={false}
          format="YYYY-MM"
        />
      </ProCard>

      <ProTable<OrgRow>
        rowKey="orgId"
        columns={columns}
        dataSource={data ?? []}
        loading={isLoading}
        search={false}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t}건` }}
        options={{ density: false, reload: false }}
        scroll={{ x: 800 }}
      />
    </PageContainer>
  );
}
