import { useRef, useState } from 'react';
import { Modal, message, Tag, Badge } from 'antd';
import {
  ModalForm, ProForm, ProFormDatePicker, ProFormDigit, ProFormSelect,
  ProFormText, ProFormTextArea, ProTable, type ActionType, type ProColumns,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import PermissionButton from '@/components/common/PermissionButton';
import { regulatoryApi, RegulatoryLimitResp, RegulatoryLimitSaveReq } from '@/api/regulatory';

const LIMIT_TYPE_OPTIONS = [
  { value: 'TOTAL_RATIO',      label: '총한도비율 (1200%)' },
  { value: 'FIRST_YEAR_RATIO', label: '1차년도한도 (35%)' },
  { value: 'INSTALLMENT_YEARS', label: '분급 연한 (7년)' },
];

const PRODUCT_CATEGORY_OPTIONS = [
  { value: 'ALL',              label: '전체 상품' },
  { value: 'LIFE',             label: '생명보험' },
  { value: 'NON_LIFE',         label: '손해보험' },
  { value: 'EXCLUDED_AUTO',    label: '자동차보험(1200%룰 제외)' },
  { value: 'EXCLUDED_HEALTH',  label: '실손의료비(1200%룰 제외)' },
];

const UNIT_OPTIONS = [
  { value: 'PERCENT', label: '% (퍼센트)' },
  { value: 'YEAR',    label: '년 (연도)' },
  { value: 'MONTH',   label: '개월' },
];

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

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

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

  const onDeactivate = (record: RegulatoryLimitResp) => {
    Modal.confirm({
      title: '규제 한도 비활성화',
      content: `[${record.limitTypeName ?? record.limitType}] 한도를 비활성화하시겠습니까?`,
      okType: 'danger',
      okText: '비활성화',
      cancelText: '취소',
      onOk: async () => {
        await regulatoryApi.deactivate(record.limitId);
        message.success('비활성화 완료');
        actionRef.current?.reload();
      },
    });
  };

  const onActivate = (record: RegulatoryLimitResp) => {
    Modal.confirm({
      title: '규제 한도 활성화',
      content: `[${record.limitTypeName ?? record.limitType}] 한도를 활성화하시겠습니까?`,
      okText: '활성화',
      cancelText: '취소',
      onOk: async () => {
        await regulatoryApi.activate(record.limitId);
        message.success('활성화 완료');
        actionRef.current?.reload();
      },
    });
  };

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

  const columns: ProColumns<RegulatoryLimitResp>[] = [
    {
      title: '한도유형', dataIndex: 'limitType', width: 160,
      render: (_, r) => (
        <Tag color={r.limitType === 'TOTAL_RATIO' ? 'red' : r.limitType === 'FIRST_YEAR_RATIO' ? 'orange' : 'blue'}>
          {r.limitTypeName ?? r.limitType}
        </Tag>
      ),
    },
    { title: '상품분류', dataIndex: 'productCategoryName', width: 160, render: (_, r) => r.productCategoryName ?? '전체 상품' },
    {
      title: '한도값', dataIndex: 'limitValue', width: 110, align: 'right',
      render: (_, r) => <strong>{Number(r.limitValue).toLocaleString()}</strong>,
    },
    { title: '단위', dataIndex: 'unitName', width: 80, render: (_, r) => r.unitName ?? r.unit },
    { title: '적용시작', dataIndex: 'effectiveFrom', width: 110 },
    { title: '적용종료', dataIndex: 'effectiveTo', width: 110, render: (v) => v ?? '현재 유효' },
    { title: '근거법령', dataIndex: 'regulationRef', width: 200, ellipsis: true },
    { title: '설명', dataIndex: 'description', ellipsis: true, search: false },
    {
      title: '상태', dataIndex: 'isActive', width: 80, align: 'center',
      render: (_, r) => r.isActive
        ? <Badge status="success" text="활성" />
        : <Badge status="default" text="비활성" />,
    },
    {
      title: '액션', valueType: 'option', width: 130, fixed: 'right',
      render: (_, r) => [
        <PermissionButton key="edit" menuCode="REGULATORY_LIMIT" permCode="UPDATE" size="small" type="link"
          onClick={() => openEdit(r)}>수정</PermissionButton>,
        r.isActive ? (
          <PermissionButton key="deact" menuCode="REGULATORY_LIMIT" permCode="UPDATE" size="small" type="link" danger
            onClick={() => onDeactivate(r)}>비활성화</PermissionButton>
        ) : (
          <PermissionButton key="act" menuCode="REGULATORY_LIMIT" permCode="UPDATE" size="small" type="link"
            onClick={() => onActivate(r)}>활성화</PermissionButton>
        ),
      ],
    },
  ];

  return (
    <PageContainer
      title="1200%룰 규제 한도 관리"
      description="보험업감독규정 제5-15조의5 — 모집수수료 총 한도(1200%), 1차년도 한도(35%), 분급 연한(7년) 관리"
    >
      <ProTable<RegulatoryLimitResp>
        actionRef={actionRef}
        rowKey="limitId"
        columns={columns}
        search={false}
        request={async () => {
          const res = await regulatoryApi.list();
          return { data: res.list, total: res.total, success: true };
        }}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        scroll={{ x: 1200 }}
        toolBarRender={() => [
          <PermissionButton key="create" menuCode="REGULATORY_LIMIT" permCode="CREATE" type="primary"
            onClick={openCreate}>+ 한도 등록</PermissionButton>,
        ]}
        dateFormatter="string"
      />

      <ModalForm
        title={modal.editId ? '규제 한도 수정' : '규제 한도 등록'}
        open={modal.open}
        onOpenChange={(o) => !o && setModal({ open: false })}
        width={620}
        layout="vertical"
        key={modal.editId ?? 'new'}
        initialValues={editRecord ? {
          ...editRecord,
          productCategory: editRecord.productCategory ?? 'ALL',
          effectiveFrom: editRecord.effectiveFrom ? dayjs(editRecord.effectiveFrom) : null,
          effectiveTo: editRecord.effectiveTo ? dayjs(editRecord.effectiveTo) : null,
        } : { productCategory: 'ALL', unit: 'PERCENT' }}
        onFinish={onSubmit}
        submitter={{ searchConfig: { submitText: modal.editId ? '수정' : '등록', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProForm.Group>
          <ProFormSelect
            name="limitType" label="한도유형" rules={[{ required: true }]} width="md"
            options={LIMIT_TYPE_OPTIONS}
          />
          <ProFormSelect
            name="productCategory" label="상품분류" width="md"
            options={PRODUCT_CATEGORY_OPTIONS}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="limitValue" label="한도값" rules={[{ required: true }]} width="md"
            min={0} fieldProps={{ precision: 2 }}
          />
          <ProFormSelect
            name="unit" label="단위" rules={[{ required: true }]} width="md"
            options={UNIT_OPTIONS}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDatePicker name="effectiveFrom" label="적용 시작일" rules={[{ required: true }]} width="md" />
          <ProFormDatePicker name="effectiveTo" label="적용 종료일 (미입력 = 현재 유효)" width="md" />
        </ProForm.Group>
        <ProFormText
          name="regulationRef" label="근거 법령" width="xl"
          placeholder="예: 보험업감독규정 제5-15조의5"
        />
        <ProFormTextArea name="description" label="설명" fieldProps={{ rows: 3 }} />
      </ModalForm>
    </PageContainer>
  );
}
