import { useRef, useState } from 'react';
import { 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 {
  installmentApi,
  type InstallmentRatioResp,
  type InstallmentRatioSaveReq,
  type InstallmentRatioSearchParam,
} from '@/api/installment';

const MENU_CODE = 'INSTALLMENT';

/** 상품분류 옵션 — 전체(null)/생명/손해/자동차제외/실손제외 */
const PRODUCT_CATEGORY_OPTIONS = [
  { value: '', label: '전체' },
  { value: 'LIFE', label: '생명' },
  { value: 'NON_LIFE', label: '손해' },
  { value: 'EXCL_AUTO', label: '자동차제외' },
  { value: 'EXCL_LOSS', label: '실손제외' },
];

const PLAN_YEAR_OPTIONS = [1, 2, 3, 4, 5, 6, 7].map((y) => ({
  value: y,
  label: `${y}차년도`,
}));

const PLAN_MONTH_OPTIONS = [
  { value: null as number | null, label: '연 단위(연차 합계)' },
  ...Array.from({ length: 12 }, (_, i) => ({
    value: i + 1,
    label: `${i + 1}회차(월)`,
  })),
];

function planYearLabel(y: number): string {
  return `${y}차년도`;
}

/** 회차 표기: NULL=연 단위, 아니면 "(연차-1)*12 + 월" 통합 회차 + 월 */
function planMonthLabel(planYear: number, planMonth: number | null): string {
  if (planMonth == null) return '연 단위';
  const seq = (planYear - 1) * 12 + planMonth;
  return `${seq}회 (${planMonth}월)`;
}

export default function InstallmentRatioList() {
  const actionRef = useRef<ActionType>();
  const [searchParam, setSearchParam] = useState<InstallmentRatioSearchParam>({
    pageNum: 1,
    pageSize: 50,
  });
  const [modalOpen, setModalOpen] = useState(false);

  const openCreate = () => {
    setModalOpen(true);
  };

  const onSubmit = async (v: any) => {
    const req: InstallmentRatioSaveReq = {
      productCategory: v.productCategory || null,
      planYear: v.planYear,
      planMonth: v.planMonth ?? null,
      ratioPercent: v.ratioPercent,
      effectiveFrom: dayjs(v.effectiveFrom).format('YYYY-MM-DD'),
      effectiveTo: v.effectiveTo ? dayjs(v.effectiveTo).format('YYYY-MM-DD') : null,
    };
    await installmentApi.create(req);
    message.success('분급비율이 등록되었습니다');
    setModalOpen(false);
    actionRef.current?.reload();
    return true;
  };

  const columns: ProColumns<InstallmentRatioResp>[] = [
    {
      title: '상품분류',
      dataIndex: 'productCategory',
      width: 130,
      search: false,
      render: (_, r) => r.productCategoryName ?? '전체',
    },
    {
      title: '분급연차',
      dataIndex: 'planYear',
      width: 110,
      align: 'center',
      search: false,
      render: (_, r) => planYearLabel(r.planYear),
    },
    {
      title: '회차(월)',
      dataIndex: 'planMonth',
      width: 130,
      align: 'center',
      search: false,
      render: (_, r) => planMonthLabel(r.planYear, r.planMonth),
    },
    {
      title: '비율(%)',
      dataIndex: 'ratioPercent',
      width: 110,
      align: 'right',
      search: false,
      render: (_, r) => (
        <strong>
          <MoneyText value={r.ratioPercent} 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) =>
        r.isActive ? (
          <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>
        ) : (
          <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>
        ),
    },
    {
      title: '상품분류 검색',
      dataIndex: 'productCategory',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: PRODUCT_CATEGORY_OPTIONS,
        allowClear: true,
        placeholder: '전체',
      },
    },
  ];

  return (
    <PageContainer
      title="분급비율 설정"
      description="1~7차년도 각 비율 설정. 회차(월) 미지정 = 연 단위(첫 달 지급), 1~12 지정 = 해당 월만 지급"
    >
      <ProTable<InstallmentRatioResp>
        actionRef={actionRef}
        rowKey="ratioId"
        columns={columns}
        request={async (params) => {
          const { productCategory, current, pageSize } = params as any;
          const p: InstallmentRatioSearchParam = {
            productCategory: productCategory || undefined,
            pageNum: current ?? 1,
            pageSize: pageSize ?? 50,
          };
          setSearchParam(p);
          const res = await installmentApi.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="분급비율 등록"
        open={modalOpen}
        onOpenChange={(o) => !o && setModalOpen(false)}
        width={560}
        layout="vertical"
        key={modalOpen ? 'open' : 'closed'}
        onFinish={onSubmit}
        submitter={{ searchConfig: { submitText: '등록', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProForm.Group>
          <ProFormSelect
            name="productCategory"
            label="상품분류"
            width="md"
            placeholder="전체 (비워두면 전체 적용)"
            options={PRODUCT_CATEGORY_OPTIONS}
            allowClear
          />
          <ProFormSelect
            name="planYear"
            label="분급연차"
            width="md"
            rules={[{ required: true, message: '분급연차를 선택하세요' }]}
            options={PLAN_YEAR_OPTIONS}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            name="planMonth"
            label="회차(월)"
            width="md"
            placeholder="비워두면 연 단위"
            tooltip="비우면 연차 합계, 1~12 선택 시 그 회차(월)만 적용"
            options={PLAN_MONTH_OPTIONS}
            allowClear
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDigit
            name="ratioPercent"
            label="비율(%)"
            width="md"
            rules={[
              { required: true, message: '비율을 입력하세요' },
              {
                validator: (_: unknown, v: number) =>
                  v > 0 ? Promise.resolve() : Promise.reject('0보다 큰 값을 입력하세요'),
              },
            ]}
            min={0.01}
            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>
  );
}
