import { useState } from 'react';
import { Alert, Form, Input, InputNumber, Modal, Space, 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 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,
  ClawbackInstallmentRow,
  ClawbackInstallmentGenerateReq,
} from '@/api/commission';
import { GRAY, RADIUS, SHADOW } from '@/theme/tokens';

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

interface SearchParam {
  receivableId?: number;
  dueMonth?: string;
  pageSize?: number;
}

const COLS: ColDef<ClawbackInstallmentRow>[] = [
  { field: 'receivableId',      headerName: '채권ID',   width: 110, pinned: 'left' },
  { field: 'installmentNo',     headerName: '회차',     width: 80,  type: 'numericColumn' },
  { field: 'installmentAmount', headerName: '분할금액', flex: 1, type: 'numericColumn', valueFormatter: (p) => fmt(p.value) },
  { field: 'dueMonth',          headerName: '납부월',   width: 110 },
  { field: 'status',            headerName: '상태',     width: 110 },
  { field: 'recoveredAt',       headerName: '회수일시', width: 160 },
];

export default function ClawbackInstallment() {
  const qc = useQueryClient();
  const [searchParams, setSearchParams] = useState<SearchParam>({ pageSize: 200 });
  const [generateOpen, setGenerateOpen] = useState(false);
  const [form] = Form.useForm<ClawbackInstallmentGenerateReq>();

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

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

  const generateMutation = useMutation({
    mutationFn: (body: ClawbackInstallmentGenerateReq) =>
      commissionApi.clawbackInstallmentGenerate(body),
    onSuccess: (result) => {
      message.success(`분할 계획 ${result.length}건 생성 완료`);
      qc.invalidateQueries({ queryKey: ['clawbackInstallment', 'list'] });
      setGenerateOpen(false);
      form.resetFields();
    },
  });

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

  const handleGenerate = async () => {
    const values = await form.validateFields();
    generateMutation.mutate(values);
  };

  const handleCancel = (row: ClawbackInstallmentRow) => Modal.confirm({
    title: '회차 취소',
    content: `채권 ${row.receivableId} / ${row.installmentNo}회차를 취소하시겠습니까?`,
    onOk: () => cancelMutation.mutateAsync(row.planId),
  });

  const pinnedRow = rows.length > 0 ? {
    installmentNo:     undefined,
    installmentAmount: rows.reduce((s, r) => s + (r.installmentAmount ?? 0), 0),
    dueMonth:          '합계',
  } as Partial<ClawbackInstallmentRow> : 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/clawback-installments 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text',  name: 'receivableId', label: '채권ID',  span: 6 },
          { type: 'month', name: 'dueMonth',      label: '납부월', span: 6 },
        ]}
        onSearch={(v) => setSearchParams({ ...v as SearchParam, pageSize: 200 })}
        onReset={() => setSearchParams({ pageSize: 200 })}
      />

      <ProCard style={cardStyle}>
        <div style={{ marginBottom: 12 }}>
          <PermissionButton menuCode="CLAWBACK_INSTALLMENT" permCode="CREATE" type="primary" onClick={() => setGenerateOpen(true)}>
            + 분할 계획 생성
          </PermissionButton>
        </div>
        <DataGrid<ClawbackInstallmentRow>
          rows={rows}
          columns={[
            ...COLS,
            {
              headerName: '액션', width: 100, pinned: 'right',
              cellRenderer: (p: { data: ClawbackInstallmentRow }) => (
                <Space>
                  <PermissionButton
                    menuCode="CLAWBACK_INSTALLMENT" permCode="UPDATE" size="small" danger
                    disabled={p.data.status !== 'SCHEDULED'}
                    onClick={() => handleCancel(p.data)}
                  >
                    취소
                  </PermissionButton>
                </Space>
              ),
            },
          ]}
          loading={isLoading}
          height={520}
          rowKey="planId"
          pinnedBottomRow={pinnedRow}
        />
      </ProCard>

      <Modal
        title="분할 계획 생성"
        open={generateOpen}
        onOk={handleGenerate}
        onCancel={() => { setGenerateOpen(false); form.resetFields(); }}
        okText="생성"
        cancelText="취소"
        confirmLoading={generateMutation.isPending}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="receivableId" label="채권 ID" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={1} placeholder="환수채권 ID" />
          </Form.Item>
          <Form.Item name="installmentCount" label="분할 회차수" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={2} max={60} placeholder="예: 12" />
          </Form.Item>
          <Form.Item name="startMonth" label="시작월(YYYYMM)" rules={[{ required: true }]}>
            <Input placeholder="예: 202602" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
