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

export default function StaticNodes() {
  const [nodeList, setNodeList] = useState<any[]>([]);
  const [uri, setUri] = useState('');
  const [customName, setCustomName] = useState('');
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editingName, setEditingName] = useState('');

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

  const handleAdd = async () => {
    if (!uri.trim()) return;
    try {
      await api.staticCreate(uri.trim(), customName.trim() || undefined);
      setUri('');
      setCustomName('');
      load();
    } catch (err: any) {
      alert(`解析失败: ${err.message}`);
    }
  };

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

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

  const handleRename = async (id: number) => {
    if (!editingName.trim()) return;
    await api.staticUpdate(id, { name: editingName.trim() });
    setEditingId(null);
    setEditingName('');
    load();
  };

  const handleKeyDown = async (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      await handleAdd();
    }
  };

  return (
    <div>
      <h2 style={styles.title}>静态节点</h2>
      <p style={styles.subtitle}>粘贴 ss:// / vmess:// / trojan:// URI 自动解析</p>

      <div style={styles.form}>
        <input
          placeholder="自定义名称（可选）"
          value={customName}
          onChange={e => setCustomName(e.target.value)}
          style={{ width: 180 }}
        />
        <input
          placeholder="粘贴节点 URI（ss:// / vmess:// / trojan://）"
          value={uri}
          onChange={e => setUri(e.target.value)}
          onKeyDown={handleKeyDown}
          style={{ flex: 1 }}
        />
        <button className="primary" onClick={handleAdd}>添加</button>
      </div>

      <table>
        <thead>
          <tr>
            <th style={{ width: 50 }}>状态</th>
            <th>名称</th>
            <th style={{ width: 80 }}>协议</th>
            <th>Surge 配置行</th>
            <th style={{ width: 80 }}>操作</th>
          </tr>
        </thead>
        <tbody>
          {nodeList.map(node => (
            <tr key={node.id}>
              <td>
                <input
                  type="checkbox"
                  className="toggle"
                  checked={!!node.enabled}
                  onChange={() => handleToggle(node.id, node.enabled)}
                />
              </td>
              <td style={{ fontFamily: 'var(--font-mono)', color: 'var(--accent)' }}>
                {editingId === node.id ? (
                  <input
                    value={editingName}
                    onChange={e => setEditingName(e.target.value)}
                    onKeyDown={e => {
                      if (e.key === 'Enter') handleRename(node.id);
                      if (e.key === 'Escape') { setEditingId(null); setEditingName(''); }
                    }}
                    onBlur={() => handleRename(node.id)}
                    autoFocus
                    style={{ width: '100%', fontSize: 12 }}
                  />
                ) : (
                  <span
                    onDoubleClick={() => { setEditingId(node.id); setEditingName(node.name); }}
                    style={{ cursor: 'pointer' }}
                    title="双击编辑名称"
                  >
                    {node.name}
                  </span>
                )}
              </td>
              <td>
                <span style={{
                  fontFamily: 'var(--font-mono)',
                  fontSize: 10,
                  padding: '2px 6px',
                  borderRadius: 'var(--radius)',
                  background: 'var(--bg-active)',
                  color: 'var(--text-secondary)',
                  textTransform: 'uppercase',
                }}>
                  {node.type}
                </span>
              </td>
              <td>
                <span className="ellipsis mono" style={{
                  fontSize: 11,
                  maxWidth: 400,
                  display: 'inline-block',
                  color: 'var(--text-secondary)',
                }}>
                  {node.surge_line}
                </span>
              </td>
              <td>
                <button className="small danger" onClick={() => handleDelete(node.id)}>
                  删除
                </button>
              </td>
            </tr>
          ))}
          {nodeList.length === 0 && (
            <tr>
              <td colSpan={5} 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,
  },
};
