import { useState, useCallback } from 'react';
import { Alert, Modal, Space, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ColDef, SelectionChangedEvent } 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 {
  withholdingTaxApi,
  WithholdingTaxReportResp,
  WithholdingTaxSearchParam,
} from '@/api/withholdingTax';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const COLUMNS: ColDef<WithholdingTaxReportResp>[] = [
  { field: 'reportYear',     headerName: '신고연도',   width: 100, pinned: 'left' },
  { field: 'reportQuarter',  headerName: '분기',       width: 80,  pinned: 'left', valueFormatter: (p) => `${p.value}Q` },
  { field: 'agentCode',      headerName: '설계사코드', width: 120 },
  { field: 'agentName',      headerName: '설계사명',   width: 120 },
  { field: 'orgName',        headerName: '소속조직',   width: 160 },
  { field: 'totalIncome',    headerName: '지급총액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'withholdingTax', headerName: '원천징수세',  flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'statusName',     headerName: '상태',       width: 90 },
  { field: 'reportedAt',     headerName: '신고일시',   width: 140 },
];

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

export default function WithholdingTaxReportList() {
  const qc = useQueryClient();
  const currentYear = dayjs().year();
  const currentQuarter = Math.ceil((dayjs().month() + 1) / 3);

  const [params, setParams] = useState<WithholdingTaxSearchParam>({
    reportYear: currentYear,
    reportQuarter: currentQuarter,
    pageSize: 500,
  });
  const [selectedRows, setSelectedRows] = useState<WithholdingTaxReportResp[]>([]);

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

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

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

  const handleSelectionChanged = useCallback((e: SelectionChangedEvent<WithholdingTaxReportResp>) => {
    setSelectedRows(e.api.getSelectedRows());
  }, []);

  const handleRegenerate = () => {
    Modal.confirm({
      title: '원천세 재집계',
      content: `${params.reportYear}년 ${params.reportQuarter}Q 데이터를 재집계하시겠습니까?`,
      okText: '재집계',
      cancelText: '취소',
      onOk: async () => {
        try {
          await withholdingTaxApi.regenerate({
            reportYear: params.reportYear ?? currentYear,
            reportQuarter: params.reportQuarter ?? currentQuarter,
          });
          message.success('재집계 완료');
          qc.invalidateQueries({ queryKey: ['withholding-tax'] });
        } catch { /* request.ts 처리 */ }
      },
    });
  };

  const handleComplete = () => {
    Modal.confirm({
      title: '신고완료 처리',
      content: `선택한 ${selectedRows.length}건을 신고완료 처리하시겠습니까?`,
      okText: '신고완료',
      cancelText: '취소',
      onOk: async () => {
        try {
          // NOTE: ids 필드명은 T18 컨트롤러 확인 후 수정 필요
          await withholdingTaxApi.complete({ ids: selectedRows.map((r) => r.reportId) });
          message.success('신고완료 처리됨');
          qc.invalidateQueries({ queryKey: ['withholding-tax'] });
          setSelectedRows([]);
        } catch { /* request.ts 처리 */ }
      },
    });
  };

  return (
    <PageContainer
      title="원천세 신고 현황"
      description="설계사별 분기 원천세 신고 집계 및 관리"
      extra={
        <Space>
          <PermissionButton menuCode="WITHHOLDING_TAX" permCode="APPROVE" onClick={handleRegenerate}>
            재집계
          </PermissionButton>
          <PermissionButton
            menuCode="WITHHOLDING_TAX"
            permCode="APPROVE"
            type="primary"
            disabled={selectedRows.length === 0}
            onClick={handleComplete}
          >
            신고완료 ({selectedRows.length}건)
          </PermissionButton>
        </Space>
      }
    >
      {isError && (
        <Alert
          type="warning"
          showIcon
          message="API 미응답"
          description="/api/withholding-tax-reports 를 확인하세요."
          style={{ marginBottom: 16 }}
        />
      )}

      <SearchForm
        conditions={[
          { type: 'text', name: 'reportYear',    label: '신고연도', span: 6 },
          { type: 'text', name: 'reportQuarter', label: '분기(1~4)', span: 6 },
          { type: 'text', name: 'agentName',     label: '설계사명',  span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as WithholdingTaxSearchParam, pageSize: 500 })}
        onReset={() => setParams({ reportYear: currentYear, reportQuarter: currentQuarter, pageSize: 500 })}
      />

      <ProCard style={cardStyle}>
        <DataGrid<WithholdingTaxReportResp>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={620}
          rowKey="reportId"
          rowSelection="multiple"
          onSelectionChanged={handleSelectionChanged}
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>
    </PageContainer>
  );
}
