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 dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import CodeBadge from '@/components/common/CodeBadge';
import MoneyText from '@/components/common/MoneyText';
import PermissionButton from '@/components/common/PermissionButton';
import { useCommonCodes } from '@/hooks/useCommonCodes';
import { ruleApi, PayoutRuleResp, PayoutRuleSaveReq } from '@/api/rule';

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

export default function PayoutRuleList() {
  const actionRef = useRef<ActionType>();
  const { data: insuranceCodes = [] } = useCommonCodes('INSURANCE_TYPE');
  const [modal, setModal] = useState<{ open: boolean; editId?: number }>({ open: false });
  const [editRecord, setEditRecord] = useState<PayoutRuleResp | null>(null);

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

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

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

  const onSubmit = async (v: any) => {
    const req: PayoutRuleSaveReq = {
      ...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.updatePayoutRule(modal.editId, req);
      message.success('수정 완료');
    } else {
      await ruleApi.createPayoutRule(req);
      message.success('등록 완료');
    }
    setModal({ open: false });
    actionRef.current?.reload();
    return true;
  };

  const columns: ProColumns<PayoutRuleResp>[] = [
    { title: '직급', dataIndex: 'gradeName', width: 100, search: false,
      render: (_, r) => <strong>{r.gradeName}</strong> },
    {
      title: '보험종류', dataIndex: 'insuranceType', width: 110,
      valueType: 'select',
      valueEnum: Object.fromEntries(insuranceCodes.map((c) => [c.code, { text: c.codeName }])),
      render: (_, r) => <CodeBadge groupCode="INSURANCE_TYPE" value={r.insuranceType} />,
    },
    { title: '회차', dataIndex: 'commissionYear', width: 70, align: 'center', search: false },
    {
      title: '지급율(%)', dataIndex: 'payoutPct', width: 100, align: 'right', search: false,
      render: (_, r) => <strong><MoneyText value={r.payoutPct} fraction={4} /></strong>,
    },
    { title: '납입조건', dataIndex: 'payMethodCond', width: 110, search: false },
    { title: '실적등급', dataIndex: 'performanceGrade', width: 100, search: false },
    { 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_PAYOUT" permCode="UPDATE" size="small" type="link"
          onClick={() => openEdit(r)}>수정</PermissionButton>,
        <PermissionButton key="del" menuCode="RULE_PAYOUT" permCode="DELETE" size="small" type="link" danger
          onClick={() => onDelete(r)}>삭제</PermissionButton>,
      ],
    },
  ];

  return (
    <PageContainer title="지급율 (시스템 → 설계사)" description="직급·보험종·회차별 설계사 지급율">
      <ProTable<PayoutRuleResp>
        actionRef={actionRef}
        rowKey="ruleId"
        columns={columns}
        request={async (params) => {
          const list = await ruleApi.payoutRules({ insuranceType: (params as any).insuranceType });
          return { data: list, total: list.length, success: true };
        }}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
        search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        toolBarRender={() => [
          <PermissionButton key="create" menuCode="RULE_PAYOUT" 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="gradeId" label="직급" rules={[{ required: true }]} width="md"
            options={GRADE_OPTIONS}
          />
          <ProFormSelect
            name="insuranceType" label="보험종류" rules={[{ required: true }]} width="md"
            options={insuranceCodes.map((c) => ({ value: c.code, label: c.codeName }))}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            name="commissionYear" label="회차" rules={[{ required: true }]} width="md"
            options={YEAR_OPTIONS}
          />
          <ProFormDigit
            name="payoutPct" label="지급율(%)" rules={[{ required: true }]} width="md"
            min={0} max={100} fieldProps={{ precision: 4 }}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="payMethodCond" label="납입조건" width="md" placeholder="MONTHLY/ALL" />
          <ProFormText name="performanceGrade" label="실적등급" width="md" placeholder="A/B/C" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDatePicker name="effectiveFrom" label="적용시작" width="md" />
          <ProFormDatePicker name="effectiveTo" label="적용종료" width="md" />
        </ProForm.Group>
      </ModalForm>
    </PageContainer>
  );
}
