import { useRef, useState } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProTable, ModalForm, ProFormDateTimePicker } from '@ant-design/pro-components';
import type { ProColumns, ActionType, ProFormInstance } from '@ant-design/pro-components';
import { Switch, message, Tag, Progress, Space } from 'antd';
import { listInviteCodes, toggleInviteCode, updateInviteCode } from '@/services/admin/api';
import { getApiErrorMessage } from '@/utils';

const isEpochDate = (v: any) => !v || String(v).startsWith('1970-01-01');

const formatDate = (v: any) => {
  if (isEpochDate(v) || v === '0001-01-01T00:00:00Z') return '-';
  const d = new Date(v);
  return isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
};

const InviteCodesPage: 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<AdminAPI.InviteCode | null>(null);

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

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

  const handleToggle = async (id: number, checked: boolean) => {
    try {
      await toggleInviteCode(id);
      message.success(checked ? t('pages.admin.inviteCodes.activated') : t('pages.admin.inviteCodes.deactivated'));
      actionRef.current?.reload();
    } catch (err: any) {
      message.error(getApiErrorMessage(err, t('pages.admin.common.toggleFailed')));
    }
  };

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

  const handleSubmit = async (values: any) => {
    if (!editRecord) return false;
    try {
      await updateInviteCode(editRecord.id, values);
      message.success(t('pages.admin.common.updateSuccess'));
      setModalOpen(false);
      actionRef.current?.reload();
      return true;
    } catch (err: any) {
      message.error(getApiErrorMessage(err, t('pages.admin.common.operationFailed')));
      return false;
    }
  };

  const columns: ProColumns<AdminAPI.InviteCode>[] = [
    { title: 'ID', dataIndex: 'id', width: 60, search: false },
    { title: t('pages.admin.inviteCodes.code'), dataIndex: 'code', width: 140, copyable: true },
    { title: t('pages.admin.inviteCodes.walletAddress'), dataIndex: 'wallet_address', width: 200, ellipsis: true },
    { title: t('pages.admin.inviteCodes.usedCount'), dataIndex: 'used_count', width: 80, search: false,
      render: (v: any, record) => (
        <span>{v} / {record.max_uses === -1 ? '∞' : record.max_uses}</span>
      ) },
    { title: t('pages.admin.inviteCodes.usage'), dataIndex: 'used_count', key: 'usage_bar', width: 140, search: false,
      render: (v: any, record) => (
        record.max_uses === -1 ? <Tag color="blue">Unlimited</Tag> :
        <Progress
          percent={record.max_uses > 0 ? Math.round((v / record.max_uses) * 100) : 0}
          size="small"
          status={v >= record.max_uses ? 'exception' : 'active'}
        />
      ) },
    { title: t('pages.admin.inviteCodes.expiresAt'), dataIndex: 'expires_at', width: 160, search: false,
      render: (v: any) => formatDate(v) === '-' ? t('pages.admin.common.never') : formatDate(v) },
    { 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.createdAt'), dataIndex: 'created_at', width: 160, search: false,
      render: (v: any) => formatDate(v) },
    {
      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>
          <Switch
            checked={record.is_active}
            onChange={(checked) => handleToggle(record.id, checked)}
            size="small"
          />
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<AdminAPI.InviteCode>
        rowKey="id"
        actionRef={actionRef}
        formRef={searchFormRef}
        search={{ onValuesChange: handleValuesChange }}
        columns={columns}
        request={async (params) => {
          const res = await listInviteCodes(params);
          return { data: res.data, success: res.success, total: res.total };
        }}
        scroll={{ x: 1100 }}
        pagination={{ pageSize: 20 }}
      />

      <ModalForm
        title={t('pages.admin.inviteCodes.editExpiry')}
        open={modalOpen}
        onOpenChange={setModalOpen}
        onFinish={handleSubmit}
        initialValues={editRecord ? { expires_at: isEpochDate(editRecord.expires_at) ? undefined : editRecord.expires_at } : {}}
        modalProps={{ destroyOnHidden: true }}
        width={400}
        layout="vertical"
      >
        <ProFormDateTimePicker
          name="expires_at"
          label={t('pages.admin.inviteCodes.expiresAt')}
          fieldProps={{ style: { width: '100%' } }}
          placeholder="Default: 2099-12-31"
        />
      </ModalForm>
    </PageContainer>
  );
};

export default InviteCodesPage;
