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 MoneyText from '@/components/common/MoneyText';
import PermissionButton from '@/components/common/PermissionButton';
import { ruleApi, OverrideRuleResp, OverrideRuleSaveReq } from '@/api/rule';

const GRADE_OPTIONS = [1, 2, 3, 4, 5, 6].map((id) => ({ value: id, label: `직급 #${id}` }));
const CALC_TYPE_OPTIONS = [
  { value: 'FLAT', label: 'FLAT (정률)' },
  { value: 'PROGRESSIVE', label: 'PROGRESSIVE (누진)' },
];

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

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

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

  const onDelete = (record: OverrideRuleResp) => {
    Modal.confirm({
      title: '오버라이드 규정 삭제',
      content: '해당 오버라이드 규정을 삭제하시겠습니까?',
      okType: 'danger',
      okText: '삭제',
      cancelText: '취소',
      onOk: async () => {
        await ruleApi.removeOverrideRule(record.overrideId);
        message.success('삭제 완료');
        actionRef.current?.reload();
      },
    });
  };

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

  const columns: ProColumns<OverrideRuleResp>[] = [
    { title: '하위 직급', dataIndex: 'fromGradeName', width: 110, search: false,
      render: (_, r) => <strong>{r.fromGradeName ?? `#${r.fromGrade}`}</strong> },
    { title: '상위 직급', dataIndex: 'toGradeName', width: 110, search: false,
      render: (_, r) => r.toGradeName ?? `#${r.toGrade}` },
    {
      title: '오버라이드율(%)', dataIndex: 'overridePct', width: 130, align: 'right', search: false,
      render: (_, r) => <strong><MoneyText value={r.overridePct} fraction={4} /></strong>,
    },
    { title: '계산방식', dataIndex: 'calcType', width: 110, search: false },
    { title: '보험종조건', dataIndex: 'insuranceTypeCond', width: 120, search: false },
    {
      title: '월 상한', dataIndex: 'capAmount', width: 130, align: 'right', search: false,
      render: (_, r) => <MoneyText value={r.capAmount} />,
    },
    { title: '적용시작', dataIndex: 'effectiveFrom', width: 110, search: false },
    { title: '적용종료', dataIndex: 'effectiveTo', width: 110, search: false },
    {
      title: '액션', valueType: 'option', width: 130, fixed: 'right',
      render: (_, r) => [
        <PermissionButton key="edit" menuCode="RULE_OVERRIDE" permCode="UPDATE" size="small" type="link"
          onClick={() => openEdit(r)}>수정</PermissionButton>,
        <PermissionButton key="del" menuCode="RULE_OVERRIDE" permCode="DELETE" size="small" type="link" danger
          onClick={() => onDelete(r)}>삭제</PermissionButton>,
      ],
    },
  ];

  return (
    <PageContainer title="오버라이드 규정" description="조직 트리 상향 분배율 (하위 → 상위 직급)">
      <ProTable<OverrideRuleResp>
        actionRef={actionRef}
        rowKey="overrideId"
        columns={columns}
        search={false}
        request={async () => {
          const list = await ruleApi.overrideRules();
          return { data: list, total: list.length, success: true };
        }}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t}건` }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        toolBarRender={() => [
          <PermissionButton key="create" menuCode="RULE_OVERRIDE" 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="fromGrade" label="하위 직급" rules={[{ required: true }]} width="md"
            options={GRADE_OPTIONS}
          />
          <ProFormSelect
            name="toGrade" label="상위 직급" rules={[{ required: true }]} width="md"
            options={GRADE_OPTIONS}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="overridePct" label="오버라이드율(%)" rules={[{ required: true }]} width="md"
            min={0} max={100} fieldProps={{ precision: 4 }}
          />
          <ProFormSelect
            name="calcType" label="계산방식" width="md"
            options={CALC_TYPE_OPTIONS}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="insuranceTypeCond" label="보험종조건" width="md" placeholder="LIFE/ALL" />
          <ProFormDigit
            name="capAmount" 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>
  );
}
