import { useRef, useState } from 'react';
import { Modal, Tag, message } from 'antd';
import {
  ModalForm,
  ProForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormSelect,
  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 MoneyText from '@/components/common/MoneyText';
import {
  chargebackGradeApi,
  type ChargebackGradeResp,
  type ChargebackGradeSaveReq,
  type ChargebackGradeSearchParam,
} from '@/api/chargeback-grade';

const MENU_CODE = 'CHARGEBACK_GRADE';

const PRODUCT_CATEGORY_OPTIONS = [
  { value: '', label: '전체' },
  { value: 'LIFE', label: '생명' },
  { value: 'NON_LIFE', label: '손해' },
  { value: 'EXCL_AUTO', label: '자동차제외' },
  { value: 'EXCL_LOSS', label: '실손제외' },
];

function ActiveBadge({ active }: { active: boolean }) {
  if (active) {
    return (
      <Tag
        style={{
          color: '#0F6E56',
          background: '#E1F5EE',
          border: '1px solid #B9E5D5',
          margin: 0,
          padding: '0 8px',
          height: 22,
          lineHeight: '20px',
          fontSize: 12,
          fontWeight: 500,
          borderRadius: 4,
        }}
      >
        활성
      </Tag>
    );
  }
  return (
    <Tag
      style={{
        color: '#666666',
        background: '#F5F5F5',
        border: '1px solid #DDDDDD',
        margin: 0,
        padding: '0 8px',
        height: 22,
        lineHeight: '20px',
        fontSize: 12,
        fontWeight: 500,
        borderRadius: 4,
      }}
    >
      비활성
    </Tag>
  );
}

export default function ChargebackGradeList() {
  const actionRef = useRef<ActionType>();
  const [searchParam, setSearchParam] = useState<ChargebackGradeSearchParam>({
    pageNum: 1,
    pageSize: 50,
  });
  const [modal, setModal] = useState<{
    open: boolean;
    editId?: number;
  }>({ open: false });
  const [editRecord, setEditRecord] = useState<ChargebackGradeResp | null>(null);

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

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

  const onDeactivate = (record: ChargebackGradeResp) => {
    Modal.confirm({
      title: '환수등급 비활성화',
      content: `경과월 구간 "${record.monthsRange}"을(를) 비활성화하시겠습니까?`,
      okType: 'danger',
      okText: '비활성화',
      cancelText: '취소',
      onOk: async () => {
        await chargebackGradeApi.deactivate(record.gradeId);
        message.success('비활성화 완료');
        actionRef.current?.reload();
      },
    });
  };

  const onSubmit = async (v: any) => {
    const req: ChargebackGradeSaveReq = {
      productCategory: v.productCategory || null,
      monthsFrom: v.monthsFrom,
      monthsTo: v.monthsTo != null && v.monthsTo !== '' ? v.monthsTo : null,
      chargebackPercent: v.chargebackPercent,
      effectiveFrom: dayjs(v.effectiveFrom).format('YYYY-MM-DD'),
      effectiveTo: v.effectiveTo ? dayjs(v.effectiveTo).format('YYYY-MM-DD') : null,
    };

    if (modal.editId) {
      await chargebackGradeApi.update(modal.editId, req);
      message.success('수정 완료');
    } else {
      await chargebackGradeApi.create(req);
      message.success('구간이 등록되었습니다');
    }
    setModal({ open: false });
    actionRef.current?.reload();
    return true;
  };

  const columns: ProColumns<ChargebackGradeResp>[] = [
    {
      title: '상품분류',
      dataIndex: 'productCategory',
      width: 130,
      search: false,
      render: (_, r) => r.productCategoryName ?? '전체',
    },
    {
      title: '경과월 구간',
      dataIndex: 'monthsRange',
      width: 160,
      search: false,
      render: (_, r) => <strong>{r.monthsRange}</strong>,
    },
    {
      title: '환수율(%)',
      dataIndex: 'chargebackPercent',
      width: 110,
      align: 'right',
      search: false,
      render: (_, r) => (
        <strong>
          <MoneyText value={r.chargebackPercent} fraction={2} />
        </strong>
      ),
    },
    {
      title: '적용시작',
      dataIndex: 'effectiveFrom',
      width: 120,
      search: false,
    },
    {
      title: '적용종료',
      dataIndex: 'effectiveTo',
      width: 120,
      search: false,
      render: (_, r) => r.effectiveTo ?? '현재유효',
    },
    {
      title: '활성',
      dataIndex: 'isActive',
      width: 80,
      align: 'center',
      search: false,
      render: (_, r) => <ActiveBadge active={r.isActive} />,
    },
    {
      title: '액션',
      valueType: 'option',
      width: 160,
      fixed: 'right',
      render: (_, r) =>
        r.isActive
          ? [
              <PermissionButton
                key="edit"
                menuCode={MENU_CODE}
                permCode="UPDATE"
                size="small"
                type="link"
                onClick={() => openEdit(r)}
              >
                수정
              </PermissionButton>,
              <PermissionButton
                key="deactivate"
                menuCode={MENU_CODE}
                permCode="UPDATE"
                size="small"
                type="link"
                danger
                onClick={() => onDeactivate(r)}
              >
                비활성화
              </PermissionButton>,
            ]
          : [],
    },
    {
      title: '상품분류 검색',
      dataIndex: 'productCategory',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: PRODUCT_CATEGORY_OPTIONS,
        allowClear: true,
        placeholder: '전체',
      },
    },
    {
      title: '기준일',
      dataIndex: 'effectiveDate',
      hideInTable: true,
      valueType: 'date',
    },
  ];

  return (
    <PageContainer
      title="환수등급 (차등환수룰) 관리"
      description="보험 해약 경과월에 따른 차등 환수율 구간 설정 (보험업감독규정)"
    >
      <ProTable<ChargebackGradeResp>
        actionRef={actionRef}
        rowKey="gradeId"
        columns={columns}
        request={async (params) => {
          const { productCategory, effectiveDate, current, pageSize } = params as any;
          const p: ChargebackGradeSearchParam = {
            productCategory: productCategory || undefined,
            effectiveDate: effectiveDate
              ? dayjs(effectiveDate).format('YYYY-MM-DD')
              : undefined,
            pageNum: current ?? 1,
            pageSize: pageSize ?? 50,
          };
          setSearchParam(p);
          const res = await chargebackGradeApi.list(p);
          return { data: res.list, total: res.total, success: true };
        }}
        pagination={{
          pageSize: searchParam.pageSize ?? 50,
          showTotal: (t) => `총 ${t.toLocaleString()}건`,
        }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        toolBarRender={() => [
          <PermissionButton
            key="create"
            menuCode={MENU_CODE}
            permCode="CREATE"
            type="primary"
            onClick={openCreate}
          >
            + 구간 등록
          </PermissionButton>,
        ]}
        dateFormatter="string"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
      />

      <ModalForm
        title={modal.editId ? '환수등급 수정' : '환수등급 구간 등록'}
        open={modal.open}
        onOpenChange={(o) => !o && setModal({ open: false })}
        width={560}
        layout="vertical"
        key={modal.editId ?? 'new'}
        initialValues={
          editRecord
            ? {
                productCategory: editRecord.productCategory ?? '',
                monthsFrom: editRecord.monthsFrom,
                monthsTo: editRecord.monthsTo ?? undefined,
                chargebackPercent: editRecord.chargebackPercent,
                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="productCategory"
            label="상품분류"
            width="md"
            placeholder="전체 (비워두면 전체 적용)"
            options={PRODUCT_CATEGORY_OPTIONS}
            allowClear
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="monthsFrom"
            label="경과월 시작"
            width="md"
            rules={[
              { required: true, message: '경과월 시작을 입력하세요' },
              {
                validator: (_: unknown, v: number) =>
                  v >= 0
                    ? Promise.resolve()
                    : Promise.reject('0 이상의 값을 입력하세요'),
              },
            ]}
            min={0}
            max={9999}
            fieldProps={{ precision: 0 }}
            placeholder="예: 0"
          />
          <ProFormDigit
            name="monthsTo"
            label="경과월 종료"
            width="md"
            min={0}
            max={9999}
            fieldProps={{ precision: 0 }}
            placeholder="비워두면 무한대"
            rules={[
              {
                validator: (_: unknown, v: number) => {
                  if (v == null) return Promise.resolve();
                  if (v >= 0) return Promise.resolve();
                  return Promise.reject('0 이상의 값을 입력하세요');
                },
              },
            ]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="chargebackPercent"
            label="환수율(%)"
            width="md"
            rules={[
              { required: true, message: '환수율을 입력하세요' },
              {
                validator: (_: unknown, v: number) =>
                  v >= 0
                    ? Promise.resolve()
                    : Promise.reject('0 이상의 값을 입력하세요'),
              },
            ]}
            min={0}
            max={100}
            fieldProps={{ precision: 2, step: 0.01 }}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDatePicker
            name="effectiveFrom"
            label="적용시작"
            width="md"
            rules={[{ required: true, message: '적용시작일을 선택하세요' }]}
          />
          <ProFormDatePicker
            name="effectiveTo"
            label="적용종료"
            width="md"
            placeholder="비워두면 현재유효"
          />
        </ProForm.Group>
      </ModalForm>
    </PageContainer>
  );
}
