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

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

  // Form state
  const [formOpen, setFormOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formName, setFormName] = useState('');
  const [formUrl, setFormUrl] = useState('');
  const [formUrlClash, setFormUrlClash] = useState('');
  const [formUrlSsr, setFormUrlSsr] = useState('');

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

  const openForm = (sub?: any) => {
    setEditingId(sub?.id ?? null);
    setFormName(sub?.name ?? '');
    setFormUrl(sub?.url ?? '');
    setFormUrlClash(sub?.url_clash ?? '');
    setFormUrlSsr(sub?.url_ssr ?? '');
    setFormOpen(true);
  };

  const closeForm = () => {
    setFormOpen(false);
    setEditingId(null);
  };

  const handleSubmit = async () => {
    if (!formName.trim() || !formUrl.trim()) return;
    if (editingId !== null) {
      await api.update(editingId, {
        name: formName.trim(),
        url: formUrl.trim(),
        url_clash: formUrlClash.trim() || null,
        url_ssr: formUrlSsr.trim() || null,
      });
    } else {
      await api.create(formName.trim(), formUrl.trim(), formUrlClash.trim(), formUrlSsr.trim());
    }
    closeForm();
    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 button */}
      {!formOpen && (
        <button className="primary" style={{ marginBottom: 16 }} onClick={() => openForm()}>
          + 添加订阅
        </button>
      )}

      {/* Add / Edit form */}
      {formOpen && (
        <div style={styles.formCard}>
          <div style={styles.formTitle}>
            {editingId !== null ? '编辑订阅' : '添加订阅'}
          </div>
          <div style={styles.fieldGroup}>
            <label style={styles.label}>名称</label>
            <input
              placeholder="名称"
              value={formName}
              onChange={e => setFormName(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>
          <div style={styles.fieldGroup}>
            <label style={styles.label}>Surge URL <span style={{ color: 'var(--accent)' }}>*</span></label>
            <input
              placeholder="https://..."
              value={formUrl}
              onChange={e => setFormUrl(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>
          <div style={styles.fieldGroup}>
            <label style={styles.label}>Clash / Stash URL <span style={styles.optional}>（选填）</span></label>
            <input
              placeholder="https://..."
              value={formUrlClash}
              onChange={e => setFormUrlClash(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>
          <div style={styles.fieldGroup}>
            <label style={styles.label}>SSR / QX / 小火箭 URL <span style={styles.optional}>（选填）</span></label>
            <input
              placeholder="https://..."
              value={formUrlSsr}
              onChange={e => setFormUrlSsr(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <button onClick={closeForm}>取消</button>
            <button className="primary" onClick={handleSubmit}>
              {editingId !== null ? '保存' : '添加'}
            </button>
          </div>
        </div>
      )}

      {/* Table */}
      <table>
        <thead>
          <tr>
            <th style={{ width: 50 }}>状态</th>
            <th>名称</th>
            <th style={{ width: 120 }}>格式</th>
            <th style={{ width: 80 }}>节点数</th>
            <th style={{ width: 140 }}>最后抓取</th>
            <th style={{ width: 170 }}>操作</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>
                <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                  <span style={styles.badge} title={sub.url}>SURGE</span>
                  {sub.url_clash && (
                    <span style={{ ...styles.badge, ...styles.badgeClash }} title={sub.url_clash}>CLASH</span>
                  )}
                  {sub.url_ssr && (
                    <span style={{ ...styles.badge, ...styles.badgeSsr }} title={sub.url_ssr}>SSR</span>
                  )}
                </div>
              </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={() => openForm(sub)}>
                    编辑
                  </button>
                  <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,
  },
  formCard: {
    background: 'var(--bg-input)',
    border: '1px solid var(--border)',
    borderRadius: 'var(--radius)',
    padding: 16,
    marginBottom: 20,
    display: 'flex' as const,
    flexDirection: 'column' as const,
    gap: 12,
  },
  formTitle: {
    fontFamily: 'var(--font-mono)' as const,
    fontSize: 12,
    color: 'var(--text-muted)',
    textTransform: 'uppercase' as const,
    letterSpacing: '0.08em',
  },
  fieldGroup: {
    display: 'flex' as const,
    flexDirection: 'column' as const,
    gap: 4,
  },
  label: {
    fontSize: 11,
    color: 'var(--text-secondary)',
    fontFamily: 'var(--font-mono)' as const,
  },
  optional: {
    color: 'var(--text-muted)',
    fontSize: 10,
  },
  badge: {
    fontSize: 10,
    fontFamily: 'var(--font-mono)' as const,
    padding: '1px 5px',
    borderRadius: 3,
    background: 'var(--bg-panel)',
    border: '1px solid var(--border)',
    color: 'var(--text-secondary)',
    cursor: 'default' as const,
    userSelect: 'none' as const,
  },
  badgeClash: {
    color: '#4ade80',
    borderColor: '#4ade8040',
  },
  badgeSsr: {
    color: '#60a5fa',
    borderColor: '#60a5fa40',
  },
};
