import { useState } from 'react';
import { Alert, Button, Space, Tabs, 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 dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import {
  commissionApi,
  IncomeLedgerRow,
  MarginSummaryRow,
  CommissionSearchParam,
} from '@/api/commission';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

const fmt = (v: unknown) => (v as number)?.toLocaleString() ?? '-';
const fmtRate = (v: unknown) => v != null ? `${((v as number) * 100).toFixed(2)}%` : '-';

const LEDGER_COLS: ColDef<IncomeLedgerRow>[] = [
  { field: 'settleMonth',    headerName: '정산월',     width: 110, pinned: 'left' },
  { field: 'contractNo',     headerName: '계약번호',   width: 140 },
  { field: 'carrierName',    headerName: '보험사',     width: 130 },
  { field: 'commissionType', headerName: '수수료유형', width: 120 },
  { field: 'premiumAmount',  headerName: '보험료',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'companyRate',    headerName: '보험사요율', width: 110, type: 'numericColumn', valueFormatter: (p) => fmtRate(p.value) },
  { field: 'incomeAmount',   headerName: '수입수수료', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',         headerName: '상태',       width: 100 },
];

const MARGIN_COLS: ColDef<MarginSummaryRow>[] = [
  { field: 'settleMonth',   headerName: '정산월',   width: 110, pinned: 'left' },
  { field: 'agentName',     headerName: '설계사',   width: 130 },
  { field: 'incomeTotal',   headerName: '수입합계', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'payoutTotal',   headerName: '지급합계', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'marginAmount',  headerName: '수지차',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'marginRate',    headerName: '수지차율', width: 110, type: 'numericColumn', valueFormatter: (p) => fmtRate(p.value) },
];

export default function IncomeCommission() {
  const qc = useQueryClient();
  const [ledgerParams, setLedgerParams] = useState<CommissionSearchParam>({
    settleMonth: dayjs().format('YYYYMM'), pageSize: 200,
  });
  const [marginParams, setMarginParams] = useState<CommissionSearchParam>({
    settleMonth: dayjs().format('YYYYMM'), pageSize: 200,
  });
  const [recalcLoading, setRecalcLoading] = useState(false);

  const { data: ledgersData, isLoading: ledgersLoading, isError: ledgersError } = useQuery({
    queryKey: ['income', 'ledgers', ledgerParams],
    queryFn: () => commissionApi.incomeLedgers(ledgerParams),
    retry: false,
  });

  const { data: marginData, isLoading: marginLoading } = useQuery({
    queryKey: ['income', 'margin', marginParams],
    queryFn: () => commissionApi.incomeMargins(marginParams),
    retry: false,
  });

  const ledgers = ledgersData?.list ?? [];
  const margins = marginData?.list ?? [];

  const pinnedLedger = ledgers.length > 0 ? {
    contractNo: '합계',
    premiumAmount: ledgers.reduce((s, r) => s + (r.premiumAmount ?? 0), 0),
    incomeAmount: ledgers.reduce((s, r) => s + (r.incomeAmount ?? 0), 0),
  } as Partial<IncomeLedgerRow> : undefined;

  const pinnedMargin = margins.length > 0 ? {
    agentName: '합계',
    incomeTotal: margins.reduce((s, r) => s + (r.incomeTotal ?? 0), 0),
    payoutTotal: margins.reduce((s, r) => s + (r.payoutTotal ?? 0), 0),
    marginAmount: margins.reduce((s, r) => s + (r.marginAmount ?? 0), 0),
  } as Partial<MarginSummaryRow> : undefined;

  const handleRecalc = async () => {
    setRecalcLoading(true);
    try {
      await commissionApi.incomeMarginRecalc(marginParams.settleMonth ?? dayjs().format('YYYYMM'));
      message.success('수지차 재계산 완료');
      qc.invalidateQueries({ queryKey: ['income', 'margin'] });
    } catch { /* request.ts 처리 */ }
    finally { setRecalcLoading(false); }
  };

  const cardStyle = { background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm };

  return (
    <PageContainer title="수입수수료/수지차" description="수입수수료 원장 조회 및 수지차 집계">
      {ledgersError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/income-commissions 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <Tabs
        defaultActiveKey="ledgers"
        items={[
          {
            key: 'ledgers',
            label: '수입원장',
            children: (
              <>
                <SearchForm
                  conditions={[
                    { type: 'text',  name: 'contractNo',  label: '계약번호', span: 6 },
                    { type: 'month', name: 'settleMonth', label: '정산월',   span: 6 },
                  ]}
                  onSearch={(v) => setLedgerParams({ ...v as CommissionSearchParam, pageSize: 200 })}
                  onReset={() => setLedgerParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
                />
                <ProCard style={cardStyle}>
                  <DataGrid<IncomeLedgerRow>
                    rows={ledgers}
                    columns={LEDGER_COLS}
                    loading={ledgersLoading}
                    height={520}
                    rowKey="incomeId"
                    pinnedBottomRow={pinnedLedger}
                  />
                </ProCard>
              </>
            ),
          },
          {
            key: 'margin',
            label: '수지차(margin)',
            children: (
              <>
                <SearchForm
                  conditions={[
                    { type: 'text',  name: 'agentName',  label: '설계사명', span: 6 },
                    { type: 'month', name: 'settleMonth', label: '정산월',  span: 6 },
                  ]}
                  onSearch={(v) => setMarginParams({ ...v as CommissionSearchParam, pageSize: 200 })}
                  onReset={() => setMarginParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
                />
                <ProCard style={cardStyle}>
                  <div style={{ marginBottom: 12 }}>
                    <PermissionButton
                      menuCode="INCOME_COMM"
                      permCode="UPDATE"
                      type="primary"
                      loading={recalcLoading}
                      onClick={handleRecalc}
                    >
                      수지차 재계산
                    </PermissionButton>
                  </div>
                  <DataGrid<MarginSummaryRow>
                    rows={margins}
                    columns={MARGIN_COLS}
                    loading={marginLoading}
                    height={520}
                    rowKey="marginId"
                    pinnedBottomRow={pinnedMargin}
                  />
                </ProCard>
              </>
            ),
          },
        ]}
      />
    </PageContainer>
  );
}
