import React, { useEffect, useState, useRef } from 'react';
import {
  Button,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Space,
  Spin,
  Switch,
  Table,
  Tag,
  Typography,
} from '@douyinfe/semi-ui';
import { IconDelete, IconEdit, IconPlus } from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';

export default function SettingsEmailQuotaRule() {
  const { t } = useTranslation();
  const { Text } = Typography;
  const [loading, setLoading] = useState(false);
  const [rules, setRules] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRule, setEditingRule] = useState(null);
  const [isEdit, setIsEdit] = useState(false);
  const modalFormRef = useRef();
  const [modalFormKey, setModalFormKey] = useState(0);

  const fetchRules = async () => {
    setLoading(true);
    try {
      const res = await API.get('/api/email_quota_rule/');
      const { success, message, data } = res.data;
      if (success) {
        setRules(data || []);
      } else {
        showError(message);
      }
    } catch {
      showError(t('获取邮箱后缀额度规则失败'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRules();
  }, []);

  const openModal = (record = null) => {
    setEditingRule(record);
    setIsEdit(record !== null);
    modalFormRef.current = null;
    setModalFormKey((k) => k + 1);
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const res = await API.delete(`/api/email_quota_rule/${id}`);
      const { success, message } = res.data;
      if (success) {
        showSuccess(t('删除成功'));
        fetchRules();
      } else {
        showError(message);
      }
    } catch {
      showError(t('删除失败'));
    }
  };

  const handleToggleEnabled = async (record) => {
    try {
      const res = await API.put(`/api/email_quota_rule/${record.id}`, {
        enabled: !record.enabled,
      });
      const { success, message } = res.data;
      if (success) {
        showSuccess(t('更新成功'));
        fetchRules();
      } else {
        showError(message);
      }
    } catch {
      showError(t('更新失败'));
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await modalFormRef.current.validate();
      const emailSuffix = (values.email_suffix || '').trim();
      if (!emailSuffix.startsWith('@')) {
        showError(t('邮箱后缀必须以 @ 开头'));
        return;
      }

      const payload = {
        email_suffix: emailSuffix,
        quota: Number(values.quota || 0),
        description: (values.description || '').trim(),
      };

      let res;
      if (isEdit && editingRule) {
        res = await API.put(`/api/email_quota_rule/${editingRule.id}`, payload);
      } else {
        payload.enabled = true;
        res = await API.post('/api/email_quota_rule/', payload);
      }

      const { success, message } = res.data;
      if (success) {
        showSuccess(t('保存成功'));
        setModalVisible(false);
        fetchRules();
      } else {
        showError(message);
      }
    } catch {
      showError(t('请检查输入'));
    }
  };

  const columns = [
    {
      title: t('邮箱后缀'),
      dataIndex: 'email_suffix',
      render: (text) => <Text strong>{text}</Text>,
    },
    {
      title: t('赠送额度'),
      dataIndex: 'quota',
      render: (val) => <Tag color='green' size='large'>{val}</Tag>,
    },
    {
      title: t('状态'),
      dataIndex: 'enabled',
      render: (val, record) => (
        <Switch
          checked={val}
          onChange={() => handleToggleEnabled(record)}
          checkedText='|'
          uncheckedText='O'
        />
      ),
    },
    {
      title: t('备注'),
      dataIndex: 'description',
      render: (text) => <Text type='tertiary'>{text || '-'}</Text>,
    },
    {
      title: t('操作'),
      render: (_, record) => (
        <Space>
          <Button
            icon={<IconEdit />}
            theme='borderless'
            onClick={() => openModal(record)}
          />
          <Popconfirm
            title={t('确认删除该规则？')}
            onConfirm={() => handleDelete(record.id)}
          >
            <Button icon={<IconDelete />} theme='borderless' type='danger' />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Spin spinning={loading}>
      <div style={{ marginBottom: 12 }}>
        <Space>
          <Button icon={<IconPlus />} onClick={() => openModal()}>
            {t('新增规则')}
          </Button>
          <Button onClick={fetchRules}>{t('刷新')}</Button>
        </Space>
      </div>
      <Table
        columns={columns}
        dataSource={rules}
        rowKey='id'
        pagination={false}
        size='small'
        empty={t('暂无规则，点击「新增规则」添加')}
      />

      <Modal
        title={isEdit ? t('编辑邮箱后缀额度规则') : t('新增邮箱后缀额度规则')}
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleModalOk}
        okText={t('保存')}
        cancelText={t('取消')}
      >
        <Form
          key={`email-quota-rule-form-${modalFormKey}`}
          initValues={
            isEdit && editingRule
              ? {
                  email_suffix: editingRule.email_suffix,
                  quota: editingRule.quota,
                  description: editingRule.description || '',
                }
              : { email_suffix: '@', quota: 0, description: '' }
          }
          getFormApi={(api) => {
            modalFormRef.current = api;
          }}
        >
          <Form.Input
            field='email_suffix'
            label={t('邮箱后缀')}
            placeholder='@example.com'
            rules={[{ required: true, message: t('请输入邮箱后缀') }]}
            extraText={t('必须以 @ 开头，如 @company.com、@edu.cn')}
          />
          <Form.InputNumber
            field='quota'
            label={t('赠送额度')}
            step={1000}
            min={0}
            rules={[{ required: true, message: t('请输入额度') }]}
            extraText={t('匹配该后缀的用户注册时获得的初始额度')}
          />
          <Form.Input
            field='description'
            label={t('备注')}
            placeholder={t('如：清华大学学生')}
          />
        </Form>
      </Modal>
    </Spin>
  );
}
