import { useState } from 'react';
import { Alert, Form, Input, InputNumber, Modal, Select, Space, Tabs, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useMutation, 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,
  LapsedReinstatementRow,
  LapsedReinstatementSaveReq,
  CommissionSearchParam,
} from '@/api/commission';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

const STATUS_OPTIONS = [
  { value: 'PENDING',    label: '대기' },
  { value: 'REPAID',     label: '재지급완료' },
  { value: 'CANCELLED',  label: '취소' },
];

const COLS: ColDef<LapsedReinstatementRow>[] = [
  { field: 'reinstatedMonth',  headerName: '부활월',   width: 110, pinned: 'left' },
  { field: 'agentName',        headerName: '설계사',   width: 130 },
  { field: 'contractNo',       headerName: '증권번호', width: 140 },
  { field: 'lapsedMonth',      headerName: '실효월',   width: 110 },
  { field: 'withheldAmount',   headerName: '보류액',   flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'repaidAmount',     headerName: '재지급액', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'status',           headerName: '상태',     width: 110 },
];

export default function LapsedReinstatement() {
  const qc = useQueryClient();
  const [searchParams, setSearchParams] = useState<CommissionSearchParam & { status?: string }>({
    settleMonth: dayjs().format('YYYYMM'), pageSize: 200,
  });
  const [createOpen, setCreateOpen] = useState(false);
  const [form] = Form.useForm<LapsedReinstatementSaveReq>();

  const { data: listData, isLoading, isError } = useQuery({
    queryKey: ['lapsedReinstatement', 'list', searchParams],
    queryFn: () => commissionApi.lapsedReinstatementList(searchParams),
    retry: false,
  });

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

  const createMutation = useMutation({
    mutationFn: (body: LapsedReinstatementSaveReq) => commissionApi.lapsedReinstatementCreate(body),
    onSuccess: () => {
      message.success('등록 완료');
      qc.invalidateQueries({ queryKey: ['lapsedReinstatement', 'list'] });
      setCreateOpen(false);
      form.resetFields();
    },
  });

  const repayMutation = useMutation({
    mutationFn: (recoveryId: number) => commissionApi.lapsedReinstatementRepay(recoveryId),
    onSuccess: () => {
      message.success('재지급 처리 완료');
      qc.invalidateQueries({ queryKey: ['lapsedReinstatement', 'list'] });
    },
  });

  const cancelMutation = useMutation({
    mutationFn: (recoveryId: number) => commissionApi.lapsedReinstatementCancel(recoveryId),
    onSuccess: () => {
      message.success('취소 완료');
      qc.invalidateQueries({ queryKey: ['lapsedReinstatement', 'list'] });
    },
  });

  const handleCreate = async () => {
    const values = await form.validateFields();
    createMutation.mutate(values);
  };

  const handleRepay = (row: LapsedReinstatementRow) => Modal.confirm({
    title: '재지급 처리',
    content: `${row.agentName} 보류액 ${fmt(row.withheldAmount)}원을 재지급 처리하시겠습니까?`,
    onOk: () => repayMutation.mutateAsync(row.recoveryId),
  });

  const handleCancel = (row: LapsedReinstatementRow) => Modal.confirm({
    title: '취소',
    content: '해당 부활 재지급 건을 취소하시겠습니까?',
    onOk: () => cancelMutation.mutateAsync(row.recoveryId),
  });

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

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

  return (
    <PageContainer title="익월부활재지급" description="실효 계약 부활 시 보류 수수료 재지급 관리">
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/lapsed-reinstatements 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text',   name: 'agentName',      label: '설계사명', span: 6 },
          { type: 'month',  name: 'settleMonth',     label: '부활월',   span: 6 },
          { type: 'code', name: 'status', label: '상태', span: 6, groupCode: 'LAPSE_RECOVERY_STATUS' },
        ]}
        onSearch={(v) => setSearchParams({ ...v as typeof searchParams, pageSize: 200 })}
        onReset={() => setSearchParams({ settleMonth: dayjs().format('YYYYMM'), pageSize: 200 })}
      />

      <ProCard style={cardStyle}>
        <div style={{ marginBottom: 12 }}>
          <PermissionButton menuCode="LAPSED_REINSTATEMENT" permCode="CREATE" type="primary" onClick={() => setCreateOpen(true)}>
            + 부활 등록
          </PermissionButton>
        </div>
        <DataGrid<LapsedReinstatementRow>
          rows={rows}
          columns={[
            ...COLS,
            {
              headerName: '액션', width: 180, pinned: 'right',
              cellRenderer: (p: { data: LapsedReinstatementRow }) => (
                <Space>
                  <PermissionButton
                    menuCode="LAPSED_REINSTATEMENT" permCode="UPDATE" size="small"
                    disabled={p.data.status !== 'PENDING'}
                    onClick={() => handleRepay(p.data)}
                  >
                    재지급
                  </PermissionButton>
                  <PermissionButton
                    menuCode="LAPSED_REINSTATEMENT" permCode="UPDATE" size="small" danger
                    disabled={p.data.status !== 'PENDING'}
                    onClick={() => handleCancel(p.data)}
                  >
                    취소
                  </PermissionButton>
                </Space>
              ),
            },
          ]}
          loading={isLoading}
          height={520}
          rowKey="recoveryId"
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>

      <Modal
        title="부활 재지급 등록"
        open={createOpen}
        onOk={handleCreate}
        onCancel={() => { setCreateOpen(false); form.resetFields(); }}
        okText="등록"
        cancelText="취소"
        confirmLoading={createMutation.isPending}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="contractId" label="계약 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} />
          </Form.Item>
          <Form.Item name="agentId" label="설계사 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} />
          </Form.Item>
          <Form.Item name="lapsedMonth" label="실효월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder="예: 202511" />
          </Form.Item>
          <Form.Item name="reinstatedMonth" label="부활월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder="예: 202512" />
          </Form.Item>
          <Form.Item name="withheldAmount" label="보류액" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
