'use client';

import { useRef, useState } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Input, InputNumber, message, Modal, Popconfirm, Space, Switch, Tag, Tooltip, Typography } from 'antd';
import { CopyOutlined, PlusOutlined } from '@ant-design/icons';
import {
  listSystemContracts,
  createSystemContract,
  updateSystemContract,
  deleteSystemContract,
} from '@/services/admin/api';
import { getApiErrorMessage } from '@/utils';


interface FormState {
  id?: number;
  name: string;
  chain_id: number;
  address: string;
  deploy_block: string;
  description: string;
  is_active: boolean;
}

const defaultForm: FormState = {
  name: '',
  chain_id: 97,
  address: '',
  deploy_block: '',
  description: '',
  is_active: true,
};

export default function SystemContractsPage() {
  const intl = useIntl();
  const t = (id: string) => intl.formatMessage({ id });

  const actionRef = useRef<ActionType>();
  const [modalOpen, setModalOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState<FormState>(defaultForm);

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

  const openEdit = (record: AdminAPI.SystemContract) => {
    setForm({
      id: record.id,
      name: record.name,
      chain_id: record.chain_id,
      address: record.address,
      deploy_block: record.deploy_block != null ? String(record.deploy_block) : '',
      description: record.description ?? '',
      is_active: record.is_active,
    });
    setModalOpen(true);
  };

  const handleSave = async () => {
    if (!form.name.trim()) { message.error(t('pages.admin.systemContracts.nameRequired')); return; }
    if (!form.address.trim()) { message.error(t('pages.admin.systemContracts.addressRequired')); return; }
    setSaving(true);
    try {
      const payload: Partial<AdminAPI.SystemContract> = {
        name: form.name.trim(),
        chain_id: form.chain_id,
        address: form.address.trim(),
        deploy_block: form.deploy_block ? Number(form.deploy_block) : undefined,
        description: form.description.trim(),
        is_active: form.is_active,
      };
      if (form.id) {
        await updateSystemContract(form.id, payload);
        message.success(t('pages.admin.common.updateSuccess'));
      } else {
        await createSystemContract(payload);
        message.success(t('pages.admin.common.createSuccess'));
      }
      setModalOpen(false);
      actionRef.current?.reload();
    } catch (e: any) {
      message.error(e?.message || t('pages.admin.common.operationFailed'));
    } finally {
      setSaving(false);
    }
  };

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

  const handleToggleActive = async (record: AdminAPI.SystemContract) => {
    try {
      await updateSystemContract(record.id, { is_active: !record.is_active });
      actionRef.current?.reload();
    } catch (err: any) {
      message.error(getApiErrorMessage(err, t('pages.admin.common.toggleFailed')));
    }
  };

  const columns: ProColumns<AdminAPI.SystemContract>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: t('pages.admin.systemContracts.name'),
      dataIndex: 'name',
      width: 160,
      render: (val) => <code style={{ fontSize: 13 }}>{val}</code>,
    },
    {
      title: t('pages.admin.systemContracts.chain'),
      dataIndex: 'chain_id',
      width: 160,
      renderFormItem: () => (
        <InputNumber placeholder="Chain ID" style={{ width: '100%' }} precision={0} />
      ),
      render: (_, record) => (
        <Tag color="gold">{record.chain_id}</Tag>
      ),
    },
    {
      title: t('pages.admin.systemContracts.address'),
      dataIndex: 'address',
      search: false,
      render: (_, record) => {
        const addr = record.address;
        if (!addr) return <span style={{ color: '#ccc' }}>—</span>;
        const short = `${addr.slice(0, 6)}...${addr.slice(-4)}`;
        return (
          <Space size={6}>
            <Tooltip title={<Typography.Text copyable={{ text: addr }} style={{ color: '#fff' }}>{addr}</Typography.Text>}>
              <code style={{ fontSize: 12, color: '#666', cursor: 'default' }}>{short}</code>
            </Tooltip>
            <Tooltip title={t('pages.admin.systemContracts.copyAddress')}>
              <CopyOutlined
                style={{ fontSize: 12, color: '#aaa', cursor: 'pointer' }}
                onClick={() => {
                  navigator.clipboard.writeText(addr);
                  message.success(t('pages.admin.systemContracts.copied'));
                }}
              />
            </Tooltip>
          </Space>
        );
      },
    },
    {
      title: t('pages.admin.systemContracts.deployBlock'),
      dataIndex: 'deploy_block',
      search: false,
      width: 120,
      render: (val) => (val != null ? val : <span style={{ color: '#ccc' }}>—</span>),
    },
    {
      title: t('pages.admin.common.description'),
      dataIndex: 'description',
      search: false,
      ellipsis: true,
    },
    {
      title: t('pages.admin.common.isActive'),
      dataIndex: 'is_active',
      width: 80,
      search: false,
      render: (_, record) => (
        <Switch
          checked={record.is_active}
          size="small"
          onChange={() => handleToggleActive(record)}
        />
      ),
    },
    {
      title: t('pages.admin.common.actions'),
      valueType: 'option',
      width: 120,
      render: (_, record) => (
        <Space>
          <a onClick={() => openEdit(record)}>{t('pages.admin.common.edit')}</a>
          <Popconfirm
            title={t('pages.admin.systemContracts.deleteTitle')}
            onConfirm={() => handleDelete(record.id)}
            okText={t('pages.admin.common.yes')}
            cancelText={t('pages.admin.common.no')}
          >
            <a style={{ color: '#ff4d4f' }}>{t('pages.admin.common.delete')}</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<AdminAPI.SystemContract>
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params) => {
          const res = await listSystemContracts(params);
          return { data: res.data ?? [], success: res.success, total: res.total ?? 0 };
        }}
        toolBarRender={() => [
          <Button key="create" type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            {t('pages.admin.systemContracts.newContract')}
          </Button>,
        ]}
        pagination={{ pageSize: 20 }}
        search={{ labelWidth: 'auto' }}
      />

      <Modal
        title={form.id ? t('pages.admin.systemContracts.editTitle') : t('pages.admin.systemContracts.createTitle')}
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        onOk={handleSave}
        confirmLoading={saving}
        okText={t('pages.admin.common.create')}
        width={560}
        destroyOnHidden
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 16 }}>
          <div>
            <label style={{ display: 'block', marginBottom: 4, fontWeight: 500 }}>{t('pages.admin.systemContracts.name')} *</label>
            <Input
              value={form.name}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              placeholder={t('pages.admin.systemContracts.namePlaceholder')}
            />
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: 4, fontWeight: 500 }}>{t('pages.admin.systemContracts.chain')} *</label>
            <InputNumber
              style={{ width: '100%' }}
              precision={0}
              min={1}
              placeholder="如 97、56、421614、1..."
              value={form.chain_id}
              onChange={(v) => setForm((f) => ({ ...f, chain_id: v ?? 0 }))}
            />
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: 4, fontWeight: 500 }}>{t('pages.admin.systemContracts.address')} *</label>
            <Input
              value={form.address}
              onChange={(e) => setForm((f) => ({ ...f, address: e.target.value }))}
              placeholder="0x..."
              style={{ fontFamily: 'monospace', fontSize: 13 }}
            />
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: 4, fontWeight: 500 }}>{t('pages.admin.systemContracts.deployBlock')}</label>
            <InputNumber
              style={{ width: '100%' }}
              value={form.deploy_block ? Number(form.deploy_block) : null}
              onChange={(v) => setForm((f) => ({ ...f, deploy_block: v != null ? String(v) : '' }))}
              placeholder={t('pages.admin.systemContracts.blockPlaceholder')}
              min={0}
              precision={0}
            />
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: 4, fontWeight: 500 }}>{t('pages.admin.common.description')}</label>
            <Input
              value={form.description}
              onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
              placeholder={t('pages.admin.systemContracts.descPlaceholder')}
            />
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Switch
              checked={form.is_active}
              onChange={(v) => setForm((f) => ({ ...f, is_active: v }))}
            />
            <span>{t('pages.admin.common.isActive')}</span>
          </div>
        </div>
      </Modal>
    </PageContainer>
  );
}
