import { useState } from 'react';
import { Alert, Modal, 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 { incomeApi, AgentAnnualIncomeResp, AgentAnnualIncomeSearchParam } from '@/api/income';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const COLUMNS: ColDef<AgentAnnualIncomeResp>[] = [
  { field: 'settleYear',       headerName: '귀속연도',     width: 100, pinned: 'left' },
  { field: 'agentCode',        headerName: '설계사코드',   width: 120 },
  { field: 'agentName',        headerName: '설계사명',     width: 120 },
  { field: 'orgName',          headerName: '소속조직',     width: 160 },
  { field: 'totalCommission',  headerName: '총수수료',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'totalTaxWithheld', headerName: '원천징수세액', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'businessIncome',   headerName: '사업소득',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'statusName',       headerName: '상태',         width: 90 },
  { field: 'updatedAt',        headerName: '최종수정',     width: 140 },
];

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

export default function AgentAnnualIncomeList() {
  const qc = useQueryClient();
  const currentYear = dayjs().year();
  const [params, setParams] = useState<AgentAnnualIncomeSearchParam>({
    settleYear: currentYear,
    pageSize: 500,
  });

  const { data, isLoading, isError } = useQuery({
    queryKey: ['annual-income', params],
    queryFn: () => incomeApi.list(params),
    retry: false,
  });

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

  const pinnedRow = rows.length > 0 ? {
    agentName: '합계',
    totalCommission:  rows.reduce((s, r) => s + (r.totalCommission ?? 0), 0),
    totalTaxWithheld: rows.reduce((s, r) => s + (r.totalTaxWithheld ?? 0), 0),
    businessIncome:   rows.reduce((s, r) => s + (r.businessIncome ?? 0), 0),
  } as Partial<AgentAnnualIncomeResp> : undefined;

  const handleRegenerate = () => {
    Modal.confirm({
      title: '연말 사업소득 재집계',
      content: `${params.settleYear ?? currentYear}년 데이터를 재집계하시겠습니까? 기존 데이터가 갱신됩니다.`,
      okText: '재집계',
      cancelText: '취소',
      onOk: async () => {
        try {
          await incomeApi.regenerate(params.settleYear ?? currentYear);
          message.success('재집계 완료');
          qc.invalidateQueries({ queryKey: ['annual-income'] });
        } catch { /* request.ts 처리 */ }
      },
    });
  };

  return (
    <PageContainer
      title="연말 사업소득 명세서"
      description="설계사별 귀속연도 사업소득 집계 현황"
      extra={
        <PermissionButton
          menuCode="ANNUAL_INCOME"
          permCode="APPROVE"
          type="primary"
          onClick={handleRegenerate}
        >
          재집계
        </PermissionButton>
      }
    >
      {isError && (
        <Alert
          type="warning"
          showIcon
          message="API 미응답"
          description="/api/agent-annual-incomes 를 확인하세요."
          style={{ marginBottom: 16 }}
        />
      )}

      <SearchForm
        conditions={[
          { type: 'text',   name: 'settleYear', label: '귀속연도', span: 6 },
          { type: 'text',   name: 'agentName',  label: '설계사명', span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as AgentAnnualIncomeSearchParam, pageSize: 500 })}
        onReset={() => setParams({ settleYear: currentYear, pageSize: 500 })}
      />

      <ProCard style={cardStyle}>
        <DataGrid<AgentAnnualIncomeResp>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={620}
          rowKey="incomeId"
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>
    </PageContainer>
  );
}
