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

export default function Subscriptions() {
  const [subs, setSubs] = useState<any[]>([]);
  const [name, setName] = useState('');
  const [url, setUrl] = useState('');
  const [fetching, setFetching] = useState<number | null>(null);

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

  const handleAdd = async () => {
    if (!name.trim() || !url.trim()) return;
    await api.create(name.trim(), url.trim());
    setName('');
    setUrl('');
    load();
  };

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

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

  const handleFetch = async (id: number) => {
    setFetching(id);
    try {
      const result = await api.fetch(id);
      alert(`抓取成功，解析到 ${result.nodeCount} 个节点`);
      load();
    } catch (err: any) {
      alert(`抓取失败: ${err.message}`);
    } finally {
      setFetching(null);
    }
  };

  return (
    <div>
      <h2 style={styles.title}>订阅源管理</h2>
      <p style={styles.subtitle}>添加和管理上游订阅链接，点击刷新按钮抓取节点</p>

      {/* Add form */}
      <div style={styles.form}>
        <input
          placeholder="名称"
          value={name}
          onChange={e => setName(e.target.value)}
          style={{ width: 160 }}
        />
        <input
          placeholder="订阅 URL"
          value={url}
          onChange={e => setUrl(e.target.value)}
          style={{ flex: 1 }}
        />
        <button className="primary" onClick={handleAdd}>添加</button>
      </div>

      {/* Table */}
      <table>
        <thead>
          <tr>
            <th style={{ width: 50 }}>状态</th>
            <th>名称</th>
            <th>URL</th>
            <th style={{ width: 80 }}>节点数</th>
            <th style={{ width: 140 }}>最后抓取</th>
            <th style={{ width: 140 }}>操作</th>
          </tr>
        </thead>
        <tbody>
          {subs.map(sub => (
            <tr key={sub.id}>
              <td>
                <input
                  type="checkbox"
                  className="toggle"
                  checked={!!sub.enabled}
                  onChange={() => handleToggle(sub.id, sub.enabled)}
                />
              </td>
              <td style={{ fontFamily: 'var(--font-mono)', color: 'var(--accent)' }}>
                {sub.name}
              </td>
              <td>
                <span className="ellipsis" style={{ maxWidth: 300, display: 'inline-block' }}>
                  {sub.url}
                </span>
              </td>
              <td style={{ fontFamily: 'var(--font-mono)' }}>
                {sub.node_count || '—'}
              </td>
              <td style={{ fontSize: 11, color: 'var(--text-secondary)' }}>
                {sub.last_fetch ? new Date(sub.last_fetch).toLocaleString() : '未抓取'}
              </td>
              <td>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button
                    className="small"
                    onClick={() => handleFetch(sub.id)}
                    disabled={fetching === sub.id}
                  >
                    {fetching === sub.id ? '抓取中...' : '刷新'}
                  </button>
                  <button className="small danger" onClick={() => handleDelete(sub.id)}>
                    删除
                  </button>
                </div>
              </td>
            </tr>
          ))}
          {subs.length === 0 && (
            <tr>
              <td colSpan={6} 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,
  },
};
