import { useRef, useState } from 'react';
import { Modal, Switch, Tag, message } from 'antd';
import {
  ModalForm, ProForm, ProFormDatePicker, ProFormSelect, ProFormText,
  ProTable, type ActionType, type ProColumns,
} from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import CodeBadge from '@/components/common/CodeBadge';
import PermissionButton from '@/components/common/PermissionButton';
import { useCommonCodes } from '@/hooks/useCommonCodes';
import { productApi, ProductResp, ProductSaveReq, ProductSearchParam } from '@/api/product';
import { companyApi } from '@/api/company';

const PAY_PERIOD_OPTIONS = [
  { value: 'MONTHLY', label: '월납' },
  { value: 'QUARTERLY', label: '분기납' },
  { value: 'ANNUAL', label: '연납' },
  { value: 'SINGLE', label: '일시납' },
];

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

  const { data: companies } = useQuery({
    queryKey: ['companies', 'all'],
    queryFn: () => companyApi.list({ pageSize: 999 }),
    enabled: modal.open,
  });

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

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

  const onDelete = (record: ProductResp) => {
    Modal.confirm({
      title: '상품 삭제',
      content: `"${record.productName}" 상품을 삭제하시겠습니까?`,
      okType: 'danger',
      okText: '삭제',
      cancelText: '취소',
      onOk: async () => {
        await productApi.remove(record.productId);
        message.success('삭제 완료');
        actionRef.current?.reload();
      },
    });
  };

  const onSubmit = async (v: any) => {
    const req: ProductSaveReq = {
      ...v,
      launchDate: v.launchDate ? dayjs(v.launchDate).format('YYYY-MM-DD') : undefined,
      endDate: v.endDate ? dayjs(v.endDate).format('YYYY-MM-DD') : undefined,
      isActive: v.isActive ? 'Y' : 'N',
    };
    if (modal.editId) {
      await productApi.update(modal.editId, req);
      message.success('수정 완료');
    } else {
      await productApi.create(req);
      message.success('등록 완료');
    }
    setModal({ open: false });
    actionRef.current?.reload();
    return true;
  };

  const columns: ProColumns<ProductResp>[] = [
    { title: '검색어', dataIndex: 'searchKeyword', hideInTable: true,
      fieldProps: { placeholder: '상품명 / 코드' } },
    {
      title: '보험종류', dataIndex: 'insuranceType', width: 110, valueType: 'select',
      valueEnum: Object.fromEntries(insuranceCodes.map((c) => [c.code, { text: c.codeName }])),
      render: (_, r) => <CodeBadge groupCode="INSURANCE_TYPE" value={r.insuranceType} />,
    },
    { title: '상품코드', dataIndex: 'productCode', width: 120, search: false },
    { title: '상품명', dataIndex: 'productName', width: 240, search: false,
      render: (_, r) => <strong>{r.productName}</strong> },
    { title: '보험사', dataIndex: 'companyName', width: 120, search: false },
    { title: '상품군', dataIndex: 'productGroup', width: 100, search: false },
    { title: '납입주기', dataIndex: 'payPeriodType', width: 100, search: false },
    { title: '판매개시', dataIndex: 'launchDate', width: 110, search: false },
    { title: '판매종료', dataIndex: 'endDate', width: 110, search: false },
    {
      title: '활성', dataIndex: 'isActive', width: 80, search: false,
      render: (_, r) => <Tag color={r.isActive === 'Y' ? 'success' : 'default'}>
        {r.isActive === 'Y' ? '활성' : '비활성'}</Tag>,
    },
    {
      title: '액션', valueType: 'option', width: 130, fixed: 'right',
      render: (_, r) => [
        <PermissionButton key="edit" menuCode="PRODUCT_PRODUCT" permCode="UPDATE" size="small" type="link"
          onClick={() => openEdit(r)}>수정</PermissionButton>,
        <PermissionButton key="del" menuCode="PRODUCT_PRODUCT" permCode="DELETE" size="small" type="link" danger
          onClick={() => onDelete(r)}>삭제</PermissionButton>,
      ],
    },
  ];

  return (
    <PageContainer title="상품 관리" description="보험사별 보험 상품 / 보험종류 / 상품군">
      <ProTable<ProductResp, ProductSearchParam>
        actionRef={actionRef}
        rowKey="productId"
        columns={columns}
        scroll={{ x: 1400 }}
        request={async (params) => {
          const { current, pageSize, ...rest } = params as any;
          const res = await productApi.list({ ...rest, pageNum: current, pageSize });
          return { data: res.list, total: res.total, success: true };
        }}
        pagination={{ pageSize: 20, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
        search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        toolBarRender={() => [
          <PermissionButton key="create" menuCode="PRODUCT_PRODUCT" 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,
          launchDate: editRecord.launchDate ? dayjs(editRecord.launchDate) : null,
          endDate: editRecord.endDate ? dayjs(editRecord.endDate) : null,
          isActive: editRecord.isActive === 'Y',
        } : { isActive: true }}
        onFinish={onSubmit}
        submitter={{ searchConfig: { submitText: modal.editId ? '수정' : '등록', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProForm.Group>
          <ProFormText
            name="productCode" label="상품코드" rules={[{ required: true }]}
            width="md" placeholder="PRD001"
            disabled={!!modal.editId}
          />
          <ProFormText
            name="productName" label="상품명" rules={[{ required: true }]}
            width="md" placeholder="삼성 종신보험 플러스"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            name="companyId" label="보험사" rules={[{ required: true }]} width="md" showSearch
            options={companies?.list.map((c) => ({ value: c.companyId, label: c.companyName })) ?? []}
          />
          <ProFormSelect
            name="insuranceType" label="보험종류" rules={[{ required: true }]} width="md"
            options={insuranceCodes.map((c) => ({ value: c.code, label: c.codeName }))}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="productGroup" label="상품군" width="md" placeholder="종신/정기/건강" />
          <ProFormSelect
            name="payPeriodType" label="납입주기" width="md"
            options={PAY_PERIOD_OPTIONS}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDatePicker name="launchDate" label="판매개시일" width="md" />
          <ProFormDatePicker name="endDate" label="판매종료일" width="md" />
        </ProForm.Group>
        <ProForm.Item name="isActive" label="활성" valuePropName="checked">
          <Switch checkedChildren="활성" unCheckedChildren="비활성" />
        </ProForm.Item>
      </ModalForm>
    </PageContainer>
  );
}
