import { useState } from 'react';
import { Alert, Radio, Space, Typography } 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, OverrideLedgerRow, OverrideLedgerSearchParam } from '@/api/commission';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const { Text } = Typography;
const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';
const fmtPct = (v: unknown) => `${((v as number) ?? 0).toFixed(2)}%`;

const COLUMNS: ColDef<OverrideLedgerRow>[] = [
  { field: 'settleMonth',      headerName: '정산월',         width: 110, pinned: 'left' },
  { field: 'fromAgentName',    headerName: '원천 설계사(From)', width: 150 },
  { field: 'toAgentName',      headerName: '수령 설계사(To)',   width: 150 },
  { field: 'orgName',          headerName: '조직',            width: 130 },
  { field: 'baseCommission',   headerName: '기준 수수료',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'overrideRate',     headerName: '오버라이드율',    width: 130, type: 'numericColumn', valueFormatter: (p) => fmtPct(p.value) },
  { field: 'overrideAmount',   headerName: '오버라이드액',    flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',           headerName: '상태',            width: 90 },
];

type FilterMode = 'both' | 'from' | 'to';

export default function OverrideLedger() {
  const [mode, setMode] = useState<FilterMode>('both');
  const [params, setParams] = useState<OverrideLedgerSearchParam>({
    settleMonth: dayjs().format('YYYYMM'),
    pageSize: 200,
  });

  const { data, isLoading, isError } = useQuery({
    queryKey: ['override', 'ledgers', params, mode],
    queryFn: () => commissionApi.overrideLedgers(params),
    retry: false,
  });

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

  // 클라이언트사이드 방향 필터
  const rows = mode === 'from'
    ? allRows.filter((r) => r.fromAgentId === params.fromAgentId)
    : mode === 'to'
    ? allRows.filter((r) => r.toAgentId === params.toAgentId)
    : allRows;

  const pinnedRow = rows.length > 0 ? {
    fromAgentName: '합계',
    baseCommission: rows.reduce((s, r) => s + (r.baseCommission ?? 0), 0),
    overrideAmount: rows.reduce((s, r) => s + (r.overrideAmount ?? 0), 0),
  } as Partial<OverrideLedgerRow> : undefined;

  return (
    <PageContainer
      title="오버라이드 원장"
      description="From-Agent → To-Agent 오버라이드 발생 원장 (조회 전용)"
      extra={
        <Space>
          <Text style={{ fontSize: 13, color: GRAY[500] }}>방향 필터:</Text>
          <Radio.Group
            value={mode}
            onChange={(e) => setMode(e.target.value)}
            optionType="button"
            buttonStyle="solid"
            size="small"
          >
            <Radio.Button value="both">전체</Radio.Button>
            <Radio.Button value="from">From 기준</Radio.Button>
            <Radio.Button value="to">To 기준</Radio.Button>
          </Radio.Group>
        </Space>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/override-ledgers 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text',  name: 'agentName',  label: '설계사명', span: 6 },
          { type: 'month', name: 'settleMonth', label: '정산월',   span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as OverrideLedgerSearchParam, pageSize: 200 })}
        onReset={() => setParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
      />

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