import { useState, useEffect } from 'react';
import { rules as api } from '../api';

const RULE_TYPES = [
  'DOMAIN', 'DOMAIN-SUFFIX', 'DOMAIN-KEYWORD',
  'IP-CIDR', 'IP-CIDR6', 'GEOIP',
  'URL-REGEX', 'USER-AGENT',
  'PROCESS-NAME', 'SUBNET',
];

const ACTIONS = ['PROXY', 'DIRECT', 'REJECT', 'REJECT-TINYGIF'];

export default function Rules() {
  const [ruleList, setRuleList] = useState<any[]>([]);
  const [type, setType] = useState('DOMAIN-SUFFIX');
  const [value, setValue] = useState('');
  const [action, setAction] = useState('PROXY');
  const [comment, setComment] = useState('');

  const load = () => api.list().then(setRuleList).catch(console.error);
  useEffect(() => { load(); }, []);

  const handleAdd = async () => {
    if (!value.trim()) return;
    await api.create({ type, value: value.trim(), action, comment: comment.trim() || undefined });
    setValue('');
    setComment('');
    load();
  };

  const handleDelete = async (id: number) => {
    await api.delete(id);
    load();
  };

  const handleToggle = async (id: number, rule: any) => {
    await api.update(id, { enabled: rule.enabled ? 0 : 1 });
    load();
  };

  const handleMoveUp = async (index: number) => {
    if (index === 0) return;
    const ids = ruleList.map(r => r.id);
    [ids[index - 1], ids[index]] = [ids[index], ids[index - 1]];
    await api.reorder(ids);
    load();
  };

  const handleMoveDown = async (index: number) => {
    if (index === ruleList.length - 1) return;
    const ids = ruleList.map(r => r.id);
    [ids[index], ids[index + 1]] = [ids[index + 1], ids[index]];
    await api.reorder(ids);
    load();
  };

  return (
    <div>
      <h2 style={styles.title}>规则管理</h2>
      <p style={styles.subtitle}>自定义规则会注入到 Surge 配置的 [Rule] 开头（优先匹配）</p>

      {/* Add form */}
      <div style={styles.form}>
        <select value={type} onChange={e => setType(e.target.value)} style={{ width: 160 }}>
          {RULE_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
        </select>
        <input
          placeholder="匹配值 (如 google.com)"
          value={value}
          onChange={e => setValue(e.target.value)}
          style={{ flex: 1 }}
        />
        <select value={action} onChange={e => setAction(e.target.value)} style={{ width: 140 }}>
          {ACTIONS.map(a => <option key={a} value={a}>{a}</option>)}
        </select>
        <input
          placeholder="备注（可选）"
          value={comment}
          onChange={e => setComment(e.target.value)}
          style={{ width: 160 }}
        />
        <button className="primary" onClick={handleAdd}>添加</button>
      </div>

      {/* Rules table */}
      <table>
        <thead>
          <tr>
            <th style={{ width: 50 }}>状态</th>
            <th style={{ width: 60 }}>排序</th>
            <th style={{ width: 140 }}>类型</th>
            <th>匹配值</th>
            <th style={{ width: 120 }}>策略</th>
            <th>备注</th>
            <th style={{ width: 60 }}>操作</th>
          </tr>
        </thead>
        <tbody>
          {ruleList.map((rule, idx) => (
            <tr key={rule.id} style={{ opacity: rule.enabled ? 1 : 0.5 }}>
              <td>
                <input
                  type="checkbox"
                  className="toggle"
                  checked={!!rule.enabled}
                  onChange={() => handleToggle(rule.id, rule)}
                />
              </td>
              <td>
                <div style={{ display: 'flex', gap: 4 }}>
                  <button
                    className="small"
                    onClick={() => handleMoveUp(idx)}
                    disabled={idx === 0}
                    style={{ padding: '2px 6px', fontSize: 10 }}
                  >▲</button>
                  <button
                    className="small"
                    onClick={() => handleMoveDown(idx)}
                    disabled={idx === ruleList.length - 1}
                    style={{ padding: '2px 6px', fontSize: 10 }}
                  >▼</button>
                </div>
              </td>
              <td style={{
                fontFamily: 'var(--font-mono)',
                fontSize: 11,
                color: 'var(--warning)',
              }}>
                {rule.type}
              </td>
              <td style={{
                fontFamily: 'var(--font-mono)',
                fontSize: 12,
                color: 'var(--accent)',
              }}>
                {rule.value}
              </td>
              <td>
                <span style={{
                  fontFamily: 'var(--font-mono)',
                  fontSize: 10,
                  padding: '2px 8px',
                  borderRadius: 'var(--radius)',
                  background: rule.action === 'PROXY' ? 'var(--accent-glow)' :
                             rule.action === 'REJECT' ? 'rgba(255, 95, 87, 0.15)' :
                             'var(--bg-active)',
                  color: rule.action === 'PROXY' ? 'var(--accent)' :
                         rule.action === 'REJECT' ? 'var(--danger)' :
                         'var(--text-secondary)',
                }}>
                  {rule.action}
                </span>
              </td>
              <td style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                {rule.comment || '—'}
              </td>
              <td>
                <button className="small danger" onClick={() => handleDelete(rule.id)}>
                  删除
                </button>
              </td>
            </tr>
          ))}
          {ruleList.length === 0 && (
            <tr>
              <td colSpan={7} style={{ textAlign: 'center', color: 'var(--text-muted)', padding: 40 }}>
                暂无自定义规则
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
}

const styles = {
  title: {
    fontFamily: 'var(--font-mono)' as const,
    fontSize: 16,
    fontWeight: 600 as const,
    color: 'var(--text-primary)',
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 12,
    color: 'var(--text-secondary)',
    marginBottom: 20,
  },
  form: {
    display: 'flex' as const,
    gap: 8,
    marginBottom: 20,
    flexWrap: 'wrap' as const,
  },
};
