import { useRef, useState } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProTable, ModalForm, ProFormText, ProFormDigit, ProFormSwitch, ProFormTextArea } from '@ant-design/pro-components';
import type { ProColumns, ActionType, ProFormInstance } from '@ant-design/pro-components';
import { Button, Popconfirm, message, Space, Tag, Row, Col } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  listVIPTiers,
  createVIPTier,
  updateVIPTier,
  deleteVIPTier,
} from '@/services/admin/api';
import { getApiErrorMessage } from '@/utils';

const VIPTiersPage: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const searchFormRef = useRef<ProFormInstance>();
  const searchTimer = useRef<ReturnType<typeof setTimeout>>();
  const [modalOpen, setModalOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<Partial<AdminAPI.VIPTier> | null>(null);

  const t = (id: string) => intl.formatMessage({ id });

  const handleValuesChange = () => {
    clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(() => searchFormRef.current?.submit(), 500);
  };

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

  const openEdit = (record: AdminAPI.VIPTier) => {
    setEditRecord(record);
    setModalOpen(true);
  };

  const handleSubmit = async (values: any) => {
    if (values.perks) {
      try { JSON.parse(values.perks); } catch {
        message.error('Perks must be valid JSON');
        return false;
      }
    }
    try {
      if (editRecord?.id) {
        await updateVIPTier(editRecord.id, values);
        message.success(t('pages.admin.common.updateSuccess'));
      } else {
        await createVIPTier(values);
        message.success(t('pages.admin.common.createSuccess'));
      }
      setModalOpen(false);
      actionRef.current?.reload();
      return true;
    } catch (err: any) {
      message.error(getApiErrorMessage(err, t('pages.admin.common.operationFailed')));
      return false;
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteVIPTier(id);
      message.success(t('pages.admin.common.deleteSuccess'));
      actionRef.current?.reload();
    } catch (err: any) {
      message.error(getApiErrorMessage(err, t('pages.admin.common.deleteFailed')));
    }
  };

  const columns: ProColumns<AdminAPI.VIPTier>[] = [
    { title: 'ID', dataIndex: 'id', width: 60, search: false },
    { title: t('pages.admin.vipTiers.tierLevel'), dataIndex: 'tier_level', width: 80, search: false },
    { title: t('pages.admin.vipTiers.tierName'), dataIndex: 'tier_name', width: 140,
      render: (v: any, record) => (
        <Tag color={record.color || 'default'}>{v}</Tag>
      ) },
    { title: t('pages.admin.vipTiers.minPoints'), dataIndex: 'min_points', width: 120, search: false },
    { title: t('pages.admin.vipTiers.maxPoints'), dataIndex: 'max_points', width: 120, search: false,
      render: (v: any) => v ?? '∞' },
    { title: t('pages.admin.vipTiers.multiplier'), dataIndex: 'multiplier', width: 100, search: false,
      render: (v: any) => `${v}x` },
    { title: t('pages.admin.vipTiers.color'), dataIndex: 'color', width: 100, search: false,
      render: (v: any) => v ? <span style={{ color: v, fontWeight: 600 }}>{v}</span> : '-' },
    { title: t('pages.admin.vipTiers.displayOrder'), dataIndex: 'display_order', width: 70, search: false },
    { title: t('pages.admin.common.isActive'), dataIndex: 'is_active', width: 80, search: false,
      render: (v: any) => <Tag color={v ? 'green' : 'red'}>{v ? t('pages.admin.common.active') : t('pages.admin.common.inactive')}</Tag> },
    {
      title: t('pages.admin.common.actions'),
      width: 120,
      search: false,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <a onClick={() => openEdit(record)}>{t('pages.admin.common.edit')}</a>
          <Popconfirm title={t('pages.admin.common.confirmDelete')} onConfirm={() => handleDelete(record.id)}>
            <a style={{ color: 'red' }}>{t('pages.admin.common.delete')}</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const initialValues = editRecord ? { ...editRecord } : {};

  return (
    <PageContainer>
      <ProTable<AdminAPI.VIPTier>
        rowKey="id"
        actionRef={actionRef}
        formRef={searchFormRef}
        search={{ onValuesChange: handleValuesChange }}
        columns={columns}
        request={async (params) => {
          const res = await listVIPTiers(params);
          return { data: res.data, success: res.success, total: res.total };
        }}
        toolBarRender={() => [
          <Button key="create" type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            {t('pages.admin.vipTiers.create')}
          </Button>,
        ]}
        scroll={{ x: 1000 }}
        pagination={{ pageSize: 20 }}
      />

      <ModalForm
        title={editRecord ? t('pages.admin.vipTiers.edit') : t('pages.admin.vipTiers.create')}
        open={modalOpen}
        onOpenChange={setModalOpen}
        onFinish={handleSubmit}
        initialValues={initialValues}
        modalProps={{ destroyOnHidden: true }}
        width={960}
        layout="vertical"
      >
        <Row gutter={16}>
          <Col span={12}><ProFormDigit name="tier_level" label={t('pages.admin.vipTiers.tierLevel')} rules={[{ required: true }]} min={0} /></Col>
          <Col span={12}><ProFormText name="tier_name" label={t('pages.admin.vipTiers.tierName')} rules={[{ required: true }]} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormDigit name="min_points" label={t('pages.admin.vipTiers.minPoints')} min={0} rules={[{ required: true }]} /></Col>
          <Col span={12}><ProFormDigit name="max_points" label={t('pages.admin.vipTiers.maxPoints')} min={0} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormDigit name="multiplier" label={t('pages.admin.vipTiers.multiplier')} min={0} fieldProps={{ step: 0.1 }} initialValue={1} /></Col>
          <Col span={12}><ProFormDigit name="display_order" label={t('pages.admin.vipTiers.displayOrder')} min={0} initialValue={0} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormText name="color" label={t('pages.admin.vipTiers.color')} placeholder="#FFD700" /></Col>
          <Col span={12}><ProFormText name="icon" label={t('pages.admin.vipTiers.icon')} /></Col>
        </Row>
        <ProFormTextArea
          name="perks"
          label={t('pages.admin.vipTiers.perks')}
          fieldProps={{ rows: 3 }}
          placeholder='["Priority support","2x Points","Early access"]'
        />
        <ProFormSwitch name="is_active" label={t('pages.admin.common.isActive')} initialValue={true} />
      </ModalForm>
    </PageContainer>
  );
};

export default VIPTiersPage;
