import { useState, useCallback } from 'react';
import { Alert, Form, Input, 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 {
  yearEndStatementApi,
  YearEndStatementResp,
  YearEndStatementSearchParam,
} from '@/api/year-end-statement';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const COLUMNS: ColDef<YearEndStatementResp>[] = [
  { field: 'statementYear',   headerName: '귀속연도', width: 100, pinned: 'left' },
  { 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: 'totalWithheld',   headerName: '원천징수세액', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'totalLocalTax',   headerName: '지방소득세', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'fileFormat',      headerName: '포맷', width: 80 },
  { field: 'fileStatusName',  headerName: '상태', width: 100 },
  { field: 'generatedAt',     headerName: '발급일시', width: 150 },
  { field: 'sentAt',          headerName: '발송일시', width: 150 },
];

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

export default function YearEndStatementList() {
  const qc = useQueryClient();
  const currentYear = dayjs().year();
  const [params, setParams] = useState<YearEndStatementSearchParam>({
    statementYear: currentYear,
    pageSize: 500,
  });
  const [selectedRows, setSelectedRows] = useState<YearEndStatementResp[]>([]);
  const [sendOpen, setSendOpen] = useState(false);
  const [sendForm] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['year-end-statements', params],
    queryFn: () => yearEndStatementApi.list(params),
    retry: false,
  });

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

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

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

  const handleRegenerate = () => {
    Modal.confirm({
      title: '연말 지급명세서 재집계',
      content: `${params.statementYear ?? currentYear}년 연말 지급명세서를 재집계하시겠습니까? 연 사업소득 집계가 반영됩니다.`,
      okText: '재집계',
      cancelText: '취소',
      onOk: async () => {
        try {
          await yearEndStatementApi.regenerate({ statementYear: params.statementYear ?? currentYear });
          message.success('재집계 완료');
          qc.invalidateQueries({ queryKey: ['year-end-statements'] });
        } catch { /* request.ts 처리 */ }
      },
    });
  };

  const handleGenerate = () => {
    Modal.confirm({
      title: '명세서 파일 발급',
      content: `선택한 ${selectedRows.length}건의 명세서 파일을 발급하시겠습니까?`,
      okText: '발급',
      cancelText: '취소',
      onOk: async () => {
        try {
          await Promise.all(selectedRows.map((r) => yearEndStatementApi.generate(r.statementId)));
          message.success('파일 발급 완료');
          qc.invalidateQueries({ queryKey: ['year-end-statements'] });
          setSelectedRows([]);
        } catch { /* request.ts 처리 */ }
      },
    });
  };

  const handleSend = async () => {
    const values = await sendForm.validateFields();
    try {
      await yearEndStatementApi.send({
        ids: selectedRows.map((r) => r.statementId),
        sentTo: values.sentTo,
      });
      message.success('발송 처리 완료');
      qc.invalidateQueries({ queryKey: ['year-end-statements'] });
      setSendOpen(false);
      sendForm.resetFields();
      setSelectedRows([]);
    } catch { /* request.ts 처리 */ }
  };

  return (
    <PageContainer
      title="연말 지급명세서"
      description="설계사 연 사업소득 지급명세서 발급 및 발송"
      extra={
        <Space>
          <PermissionButton menuCode="YEAR_END_STMT" permCode="EXECUTE" onClick={handleRegenerate}>
            재집계
          </PermissionButton>
          <PermissionButton menuCode="YEAR_END_STMT" permCode="EXECUTE"
            disabled={selectedRows.length === 0} onClick={handleGenerate}>
            파일 발급 ({selectedRows.length}건)
          </PermissionButton>
          <PermissionButton menuCode="YEAR_END_STMT" permCode="UPDATE"
            type="primary" disabled={selectedRows.length === 0} onClick={() => setSendOpen(true)}>
            발송 처리 ({selectedRows.length}건)
          </PermissionButton>
        </Space>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답"
          description="/api/year-end-statements 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text', name: 'statementYear', label: '귀속연도', span: 6 },
          { type: 'text', name: 'fileStatus',    label: '상태(DRAFT/GENERATED/SENT)', span: 8 },
        ]}
        onSearch={(v) => setParams({ ...v as YearEndStatementSearchParam, pageSize: 500 })}
        onReset={() => setParams({ statementYear: currentYear, pageSize: 500 })}
      />

      <ProCard style={cardStyle}>
        <DataGrid<YearEndStatementResp>
          rows={rows}
          columns={COLUMNS}
          loading={isLoading}
          height={560}
          rowKey="statementId"
          rowSelection="multiple"
          onSelectionChanged={handleSelectionChanged}
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>

      {/* 발송 처리 */}
      <Modal
        title="명세서 발송 처리"
        open={sendOpen}
        onOk={handleSend}
        onCancel={() => { setSendOpen(false); sendForm.resetFields(); }}
        okText="발송"
        cancelText="취소"
      >
        <p>선택한 {selectedRows.length}건의 명세서를 발송 처리합니다.</p>
        <Form form={sendForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item name="sentTo" label="발송처"
            rules={[{ required: true, message: '발송처를 입력하세요' }]}>
            <Input placeholder="예: 이메일 / 내부공유 경로" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
