import { useRef, useState } from 'react';
import { Modal, message } from 'antd';
import {
  ModalForm, ProForm, ProFormDatePicker, ProFormDigit, ProFormSelect, ProFormText,
  ProTable, type ActionType, type ProColumns,
} from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import MoneyText from '@/components/common/MoneyText';
import PermissionButton from '@/components/common/PermissionButton';
import { ruleApi, CommissionRateResp, CommissionRateSaveReq } from '@/api/rule';
import { productApi } from '@/api/product';

const GRADE_OPTIONS = [1, 2, 3, 4, 5].map((y) => ({ value: y, label: `${y}년차` }));

export default function CommissionRateList() {
  const actionRef = useRef<ActionType>();
  const [modal, setModal] = useState<{ open: boolean; editId?: number }>({ open: false });
  const [editRecord, setEditRecord] = useState<CommissionRateResp | null>(null);

  const { data: products } = useQuery({
    queryKey: ['products', 'all'],
    queryFn: () => productApi.list({ pageSize: 999 }),
    enabled: modal.open,
  });

  const openCreate = () => {
    setEditRecord(null);
    setModal({ open: true });
  };

  const openEdit = (record: CommissionRateResp) => {
    setEditRecord(record);
    setModal({ open: true, editId: record.rateId });
  };

  const onDelete = (record: CommissionRateResp) => {
    Modal.confirm({
      title: '수수료율 삭제',
      content: '해당 수수료율을 삭제하시겠습니까?',
      okType: 'danger',
      okText: '삭제',
      cancelText: '취소',
      onOk: async () => {
        await ruleApi.removeCommissionRate(record.rateId);
        message.success('삭제 완료');
        actionRef.current?.reload();
      },
    });
  };

  const onSubmit = async (v: any) => {
    const req: CommissionRateSaveReq = {
      ...v,
      effectiveFrom: v.effectiveFrom ? dayjs(v.effectiveFrom).format('YYYY-MM-DD') : undefined,
      effectiveTo: v.effectiveTo ? dayjs(v.effectiveTo).format('YYYY-MM-DD') : undefined,
    };
    if (modal.editId) {
      await ruleApi.updateCommissionRate(modal.editId, req);
      message.success('수정 완료');
    } else {
      await ruleApi.createCommissionRate(req);
      message.success('등록 완료');
    }
    setModal({ open: false });
    actionRef.current?.reload();
    return true;
  };

  const columns: ProColumns<CommissionRateResp>[] = [
    { title: '상품ID', dataIndex: 'productId', width: 90 },
    { title: '상품명', dataIndex: 'productName', width: 200, search: false },
    { title: '회차', dataIndex: 'commissionYear', width: 70, align: 'center', search: false },
    {
      title: '수수료율(%)', dataIndex: 'ratePct', width: 110, align: 'right', search: false,
      render: (_, r) => <strong><MoneyText value={r.ratePct} fraction={4} /></strong>,
    },
    { title: '납입조건', dataIndex: 'payMethodCond', width: 110, search: false },
    {
      title: '최소보험료', dataIndex: 'minPremium', width: 130, align: 'right', search: false,
      render: (_, r) => <MoneyText value={r.minPremium} />,
    },
    { title: '적용시작', dataIndex: 'effectiveFrom', width: 110, search: false },
    { title: '적용종료', dataIndex: 'effectiveTo', width: 110, search: false },
    { title: '버전', dataIndex: 'version', width: 60, align: 'center', search: false },
    {
      title: '액션', valueType: 'option', width: 130, fixed: 'right',
      render: (_, r) => [
        <PermissionButton key="edit" menuCode="RULE_COMMISSION" permCode="UPDATE" size="small" type="link"
          onClick={() => openEdit(r)}>수정</PermissionButton>,
        <PermissionButton key="del" menuCode="RULE_COMMISSION" permCode="DELETE" size="small" type="link" danger
          onClick={() => onDelete(r)}>삭제</PermissionButton>,
      ],
    },
  ];

  return (
    <PageContainer title="수수료율 (보험사 → 시스템)" description="상품·회차별 보험사 통보 수수료율">
      <ProTable<CommissionRateResp>
        actionRef={actionRef}
        rowKey="rateId"
        columns={columns}
        search={false}
        request={async () => {
          const list = await ruleApi.commissionRates();
          return { data: list, total: list.length, success: true };
        }}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        toolBarRender={() => [
          <PermissionButton key="create" menuCode="RULE_COMMISSION" permCode="CREATE" type="primary"
            onClick={openCreate}>+ 수수료율 등록</PermissionButton>,
        ]}
        dateFormatter="string"
      />

      <ModalForm
        title={modal.editId ? '수수료율 수정' : '수수료율 등록'}
        open={modal.open}
        onOpenChange={(o) => !o && setModal({ open: false })}
        width={580}
        layout="vertical"
        key={modal.editId ?? 'new'}
        initialValues={editRecord ? {
          ...editRecord,
          effectiveFrom: editRecord.effectiveFrom ? dayjs(editRecord.effectiveFrom) : null,
          effectiveTo: editRecord.effectiveTo ? dayjs(editRecord.effectiveTo) : null,
        } : undefined}
        onFinish={onSubmit}
        submitter={{ searchConfig: { submitText: modal.editId ? '수정' : '등록', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProForm.Group>
          <ProFormSelect
            name="productId" label="상품" rules={[{ required: true }]} width="md" showSearch
            options={products?.list.map((p) => ({ value: p.productId, label: p.productName })) ?? []}
          />
          <ProFormSelect
            name="commissionYear" label="회차" rules={[{ required: true }]} width="md"
            options={GRADE_OPTIONS}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="ratePct" label="수수료율(%)" rules={[{ required: true }]} width="md"
            min={0} max={100} fieldProps={{ precision: 4 }}
          />
          <ProFormText name="payMethodCond" label="납입조건" width="md" placeholder="MONTHLY/ALL" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="minPremium" label="최소보험료" width="md" min={0}
            fieldProps={{ formatter: (v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDatePicker name="effectiveFrom" label="적용시작" width="md" />
          <ProFormDatePicker name="effectiveTo" label="적용종료" width="md" />
        </ProForm.Group>
      </ModalForm>
    </PageContainer>
  );
}
