import { useRef, useState } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProTable, ModalForm, ProFormText, ProFormDigit, ProFormSelect } from '@ant-design/pro-components';
import type { ProColumns, ActionType, ProFormInstance } from '@ant-design/pro-components';
import { message, Space, Tag } from 'antd';
import { listUsers, updateUser } from '@/services/admin/api';
import { getApiErrorMessage } from '@/utils';

const UsersPage: 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.User | null>(null);

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

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

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

  const handleSubmit = async (values: any) => {
    if (!editRecord) return false;
    try {
      await updateUser(editRecord.wallet_address, 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.updateFailed')));
      return false;
    }
  };

  const columns: ProColumns<AdminAPI.User>[] = [
    { title: t('pages.admin.users.walletAddress'), dataIndex: 'wallet_address', width: 200, ellipsis: true,
      copyable: true },
    { title: t('pages.admin.users.nickname'), dataIndex: 'nickname', width: 140 },
    { title: t('pages.admin.users.memberTier'), dataIndex: 'member_tier', width: 100, search: false,
      render: (v: any) => <Tag color="blue">{v || '-'}</Tag> },
    { title: t('pages.admin.users.vipLevel'), dataIndex: 'vip_level', width: 90, search: false },
    { title: t('pages.admin.users.totalPoints'), dataIndex: 'total_points', width: 120, search: false },
    { title: t('pages.admin.users.globalRank'), dataIndex: 'global_rank', width: 100, search: false,
      render: (v: any) => v ?? '-' },
    { title: t('pages.admin.users.referrerWallet'), dataIndex: 'referrer_wallet', width: 180, search: false,
      ellipsis: true, render: (v: any) => v || '-' },
    { title: t('pages.admin.users.inviteCode'), dataIndex: 'invite_code', width: 120, search: false },
    { title: t('pages.admin.users.directInvites'), dataIndex: 'direct_invites_count', width: 110, search: false },
    { title: t('pages.admin.users.joinedAt'), dataIndex: 'created_at', width: 160, search: false,
      render: (v: any) => v ? new Date(v).toLocaleDateString() : '-' },
    {
      title: t('pages.admin.common.actions'),
      width: 80,
      search: false,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <a onClick={() => openEdit(record)}>{t('pages.admin.common.edit')}</a>
        </Space>
      ),
    },
  ];

  const initialValues = editRecord
    ? {
        nickname: editRecord.nickname,
        member_tier: editRecord.member_tier,
        vip_level: editRecord.vip_level,
        total_points: editRecord.total_points,
        global_rank: editRecord.global_rank,
      }
    : {};

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

      <ModalForm
        title={`${t('pages.admin.users.edit')}: ${editRecord?.wallet_address?.slice(0, 10)}...`}
        open={modalOpen}
        onOpenChange={setModalOpen}
        onFinish={handleSubmit}
        initialValues={initialValues}
        modalProps={{ destroyOnHidden: true }}
        width={480}
        layout="vertical"
      >
        <ProFormText name="nickname" label={t('pages.admin.users.nickname')} />
        <ProFormSelect
          name="member_tier"
          label={t('pages.admin.users.memberTier')}
          options={[
            { label: 'Basic', value: 'basic' },
            { label: 'Silver', value: 'silver' },
            { label: 'Gold', value: 'gold' },
            { label: 'Platinum', value: 'platinum' },
          ]}
        />
        <ProFormDigit name="vip_level" label={t('pages.admin.users.vipLevel')} min={0} />
        <ProFormDigit name="total_points" label={t('pages.admin.users.totalPoints')} min={0} />
        <ProFormDigit name="global_rank" label={t('pages.admin.users.globalRank')} min={1} />
      </ModalForm>
    </PageContainer>
  );
};

export default UsersPage;
