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 { vatApi, VatReportResp, VatSearchParam } from '@/api/vat';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const COLUMNS: ColDef<VatReportResp>[] = [
  { field: 'reportYear',     headerName: '신고연도',   width: 100, pinned: 'left' },
  { field: 'reportQuarter',  headerName: '분기',       width: 80,  pinned: 'left', valueFormatter: (p) => `${p.value}Q` },
  { field: 'salesAmount',    headerName: '매출액',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'salesVat',       headerName: '매출세액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'purchaseAmount', headerName: '매입액',     flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'purchaseVat',    headerName: '매입세액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'payableVat',     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 VatReportList() {
  const qc = useQueryClient();
  const currentYear = dayjs().year();
  const currentQuarter = Math.ceil((dayjs().month() + 1) / 3);

  const [params, setParams] = useState<VatSearchParam>({
    reportYear: currentYear,
    reportQuarter: currentQuarter,
    pageSize: 200,
  });
  const [selectedRows, setSelectedRows] = useState<VatReportResp[]>([]);

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

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

  const pinnedRow = rows.length > 0 ? {
    reportYear: '합계' as unknown as number,
    salesAmount:    rows.reduce((s, r) => s + (r.salesAmount ?? 0), 0),
    salesVat:       rows.reduce((s, r) => s + (r.salesVat ?? 0), 0),
    purchaseAmount: rows.reduce((s, r) => s + (r.purchaseAmount ?? 0), 0),
    purchaseVat:    rows.reduce((s, r) => s + (r.purchaseVat ?? 0), 0),
    payableVat:     rows.reduce((s, r) => s + (r.payableVat ?? 0), 0),
  } as Partial<VatReportResp> : undefined;

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

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

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

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

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

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