import { useState } from 'react';
import { Alert } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import type { ColDef } from '@ag-grid-community/core';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import { commissionApi, CommissionMasterRow, CommissionSearchParam } from '@/api/commission';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';

const COLUMNS: ColDef<CommissionMasterRow>[] = [
  { field: 'settleMonth',        headerName: '정산월',     width: 110, pinned: 'left' },
  { field: 'agentName',          headerName: '설계사',     width: 120, pinned: 'left' },
  { field: 'commissionTypeName', headerName: '수수료 종류', width: 140 },
  { field: 'grossAmount',        headerName: '총수수료',    flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'netAmount',          headerName: '실지급',      flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',             headerName: '상태',        width: 100 },
];

export default function CommissionMaster() {
  const [params, setParams] = useState<CommissionSearchParam>({
    settleMonth: dayjs().format('YYYYMM'),
    pageSize: 200,
  });

  const { data, isLoading, isError } = useQuery({
    queryKey: ['commission', 'master', params],
    queryFn: () => commissionApi.masterList(params),
    retry: false,
  });

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

  const pinnedRow = rows.length > 0 ? {
    agentName: '합계',
    commissionTypeName: '',
    grossAmount: rows.reduce((s, r) => s + (r.grossAmount ?? 0), 0),
    netAmount: rows.reduce((s, r) => s + (r.netAmount ?? 0), 0),
  } as Partial<CommissionMasterRow> : undefined;

  return (
    <PageContainer
      title="수수료 통합 마스터"
      description="설계사+정산월 기준 9종 수수료 통합 조회"
    >
      <SearchForm
        conditions={[
          { type: 'text',  name: 'agentName',   label: '설계사명',    span: 6 },
          { type: 'month', name: 'settleMonth',  label: '정산월',      span: 6 },
          { type: 'code',  name: 'commissionType', label: '수수료 종류', groupCode: 'COMMISSION_TYPE', span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as CommissionSearchParam, pageSize: 200 })}
        onReset={() => setParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
      />

      {isError && (
        <Alert type="warning" showIcon
          message="API 미응답"
          description="/api/commissions 를 확인하세요."
          style={{ marginBottom: 16 }}
        />
      )}

      <ProCard style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm }}>
        <DataGrid<CommissionMasterRow>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={600}
          rowKey="masterId"
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>
    </PageContainer>
  );
}
