import { useRef, useState } from 'react';
import { Modal, Switch, Tag, 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, ChargebackRuleResp, ChargebackRuleSaveReq } from '@/api/rule';

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

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

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

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

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

  const columns: ProColumns<ChargebackRuleResp>[] = [
    { title: '보험사', dataIndex: 'companyCode', width: 100, search: false,
      render: (_, r) => <strong>{r.companyCode}</strong> },
    {
      title: '보험종', dataIndex: 'insuranceType', width: 110, search: false,
      render: (_, r) => <CodeBadge groupCode="INSURANCE_TYPE" value={r.insuranceType} />,
    },
    { title: '실효 시작월', dataIndex: 'lapseMonthFrom', width: 100, align: 'center', search: false },
    { title: '실효 종료월', dataIndex: 'lapseMonthTo', width: 100, align: 'center', search: false },
    {
      title: '환수율(%)', dataIndex: 'cbRate', width: 110, align: 'right', search: false,
      render: (_, r) => <strong><MoneyText value={r.cbRate} fraction={4} /></strong>,
    },
    {
      title: '오버라이드 포함', dataIndex: 'includeOverride', width: 130, align: 'center', search: false,
      render: (_, r) => <Tag color={r.includeOverride === 'Y' ? 'success' : 'default'}>
        {r.includeOverride === 'Y' ? '포함' : '제외'}</Tag>,
    },
    {
      title: '분할 가능', dataIndex: 'installmentAllowed', width: 100, align: 'center', search: false,
      render: (_, r) => <Tag color={r.installmentAllowed === 'Y' ? 'success' : 'default'}>
        {r.installmentAllowed === 'Y' ? '허용' : '불가'}</Tag>,
    },
    { title: '최대 분할', dataIndex: 'maxInstallments', width: 90, align: 'right', search: false },
    { 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_CHARGEBACK" permCode="UPDATE" size="small" type="link"
          onClick={() => openEdit(r)}>수정</PermissionButton>,
        <PermissionButton key="del" menuCode="RULE_CHARGEBACK" permCode="DELETE" size="small" type="link" danger
          onClick={() => onDelete(r)}>삭제</PermissionButton>,
      ],
    },
  ];

  return (
    <PageContainer title="환수 규정" description="실효 계약 환수율 / 분할환수 정책">
      <ProTable<ChargebackRuleResp>
        actionRef={actionRef}
        rowKey="cbRuleId"
        columns={columns}
        search={false}
        request={async () => {
          const list = await ruleApi.chargebackRules();
          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_CHARGEBACK" 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,
          includeOverride: editRecord.includeOverride === 'Y',
          installmentAllowed: editRecord.installmentAllowed === 'Y',
          effectiveFrom: editRecord.effectiveFrom ? dayjs(editRecord.effectiveFrom) : null,
          effectiveTo: editRecord.effectiveTo ? dayjs(editRecord.effectiveTo) : null,
        } : { includeOverride: false, installmentAllowed: false }}
        onFinish={onSubmit}
        submitter={{ searchConfig: { submitText: modal.editId ? '수정' : '등록', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProForm.Group>
          <ProFormText
            name="companyCode" label="보험사코드" rules={[{ required: true }]}
            width="md" placeholder="SAMSUNG"
          />
          <ProFormSelect
            name="insuranceType" label="보험종류" rules={[{ required: true }]} width="md"
            options={insuranceCodes.map((c) => ({ value: c.code, label: c.codeName }))}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="lapseMonthFrom" label="실효 시작월" rules={[{ required: true }]} width="md"
            min={1} max={120}
          />
          <ProFormDigit
            name="lapseMonthTo" label="실효 종료월" rules={[{ required: true }]} width="md"
            min={1} max={120}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="cbRate" label="환수율(%)" rules={[{ required: true }]} width="md"
            min={0} max={100} fieldProps={{ precision: 4 }}
          />
          <ProFormDigit
            name="maxInstallments" label="최대 분할횟수" width="md" min={1} max={36}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProForm.Item name="includeOverride" label="오버라이드 포함" valuePropName="checked">
            <Switch checkedChildren="포함" unCheckedChildren="제외" />
          </ProForm.Item>
          <ProForm.Item name="installmentAllowed" label="분할환수 허용" valuePropName="checked" style={{ marginLeft: 32 }}>
            <Switch checkedChildren="허용" unCheckedChildren="불가" />
          </ProForm.Item>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDatePicker name="effectiveFrom" label="적용시작" width="md" />
          <ProFormDatePicker name="effectiveTo" label="적용종료" width="md" />
        </ProForm.Group>
      </ModalForm>
    </PageContainer>
  );
}
