import { useState, useEffect, useCallback } from 'react';
import {
  adminListServers,
  adminUpdateServer,
  adminDeleteServer,
  adminReorderServers,
} from '../../api/central';
import './AdminPanel.css';

type Row = { id: string; name: string; url: string; enabled: boolean; sortOrder: number; agentKey?: string };

const formatServerUrl = (url: string) => {
  let formatted = url.trim();
  if (formatted.endsWith('.op')) {
    formatted = formatted.slice(0, -3) + '.top';
  }
  if (formatted && !/^https?:\/\//i.test(formatted)) {
    return `http://${formatted}`;
  }
  return formatted;
};

export const AdminPanel = ({
  token,
  onClose,
  onSessionInvalid,
  onSaved,
}: {
  token: string;
  onClose: () => void;
  onSessionInvalid: () => void;
  onSaved?: () => void;
}) => {
  const [rows, setRows] = useState<Row[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [editId, setEditId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({ name: '', url: '', enabled: true });

  const load = useCallback(async () => {
    setErr(null);
    try {
      const list = await adminListServers(token);
      setRows(list);
    } catch (e) {
      if (e instanceof Error && e.message === 'UNAUTHORIZED') {
        onSessionInvalid();
        return;
      }
      setErr(e instanceof Error ? e.message : '加载失败');
    } finally {
      setLoading(false);
    }
  }, [token, onSessionInvalid]);

  useEffect(() => {
    void load();
  }, [load]);

  const startEdit = (r: Row) => {
    setEditId(r.id);
    setEditForm({ name: r.name, url: r.url, enabled: r.enabled });
  };

  const saveEdit = async () => {
    if (!editId) return;
    try {
      const u = editForm.url.trim();
      await adminUpdateServer(token, editId, {
        name: editForm.name.trim(),
        ...(u ? { url: formatServerUrl(u) } : { url: '' }),
        enabled: editForm.enabled,
      });
      setEditId(null);
      await load();
      onSaved?.();
    } catch (e) {
      alert(e instanceof Error ? e.message : '保存失败');
    }
  };

  const remove = async (id: string) => {
    if (!confirm('确定删除该监控节点？')) return;
    try {
      await adminDeleteServer(token, id);
      await load();
      onSaved?.();
    } catch (e) {
      alert(e instanceof Error ? e.message : '删除失败');
    }
  };

  const copyServerId = useCallback((id: string) => {
    void navigator.clipboard.writeText(id).catch(() => {
      window.prompt('请手动复制（环境变量 SERVER_ID）', id);
    });
  }, []);

  const copyAgentKey = useCallback((key: string) => {
    void navigator.clipboard.writeText(key).catch(() => {
      window.prompt('请手动复制（环境变量 AGENT_KEY）', key);
    });
  }, []);

  const move = async (index: number, dir: -1 | 1) => {
    const j = index + dir;
    if (j < 0 || j >= rows.length) return;
    const next = [...rows];
    [next[index], next[j]] = [next[j], next[index]];
    const ids = next.map((r) => r.id);
    setRows(next);
    try {
      await adminReorderServers(token, ids);
      await load();
      onSaved?.();
    } catch (e) {
      alert(e instanceof Error ? e.message : '排序失败');
      void load();
    }
  };

  return (
    <div className="admin-overlay" role="dialog" aria-modal="true">
      <div className="admin-panel">
        <div className="admin-panel-header">
          <h2>监控管理后台</h2>
          <button type="button" className="admin-close" onClick={onClose} title="关闭">
            ×
          </button>
        </div>
        <p className="admin-hint">
          节点由采集端 gRPC 上报后出现在列表中。环境变量 CENTRAL_GRPC、<strong>SERVER_ID 须为下表「节点 ID」列的完整 UUID</strong>
          （勿把「名称」当成 SERVER_ID）、AGENT_KEY 与「节点密钥」一致。看板经 WebSocket
          拉取中心内存快照；「备注链接」可选，可在行内编辑。
        </p>

        {loading ? (
          <p className="admin-loading">加载中…</p>
        ) : (
          <>
            {err && <p className="admin-error">{err}</p>}

            <div className="admin-table-wrap">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>顺序</th>
                    <th>名称</th>
                    <th>节点 ID（SERVER_ID）</th>
                    <th>备注链接</th>
                    <th>节点密钥 (gRPC)</th>
                    <th>启用</th>
                    <th />
                  </tr>
                </thead>
                <tbody>
                  {rows.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="admin-empty">
                        暂无节点；请确认采集端已配置并连接中心，成功上报后将显示在此。
                      </td>
                    </tr>
                  ) : (
                    rows.map((r, i) => (
                      <tr key={r.id}>
                        <td>
                          <div className="admin-order-btns">
                            <button type="button" title="上移" onClick={() => void move(i, -1)} disabled={i === 0}>
                              ↑
                            </button>
                            <button
                              type="button"
                              title="下移"
                              onClick={() => void move(i, 1)}
                              disabled={i === rows.length - 1}
                            >
                              ↓
                            </button>
                          </div>
                        </td>
                        <td>
                          {editId === r.id ? (
                            <input
                              value={editForm.name}
                              onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
                            />
                          ) : (
                            r.name
                          )}
                        </td>
                        <td className="admin-server-id-cell">
                          <code className="admin-server-id" title={r.id}>
                            {r.id}
                          </code>
                          <button
                            type="button"
                            className="admin-btn admin-btn-ghost"
                            title="复制为采集端 SERVER_ID"
                            onClick={() => copyServerId(r.id)}
                          >
                            复制
                          </button>
                        </td>
                        <td>
                          {editId === r.id ? (
                            <input
                              className="admin-url-input"
                              value={editForm.url}
                              onChange={(e) => setEditForm({ ...editForm, url: e.target.value })}
                            />
                          ) : r.url ? (
                            <code>{r.url}</code>
                          ) : (
                            <span className="admin-muted">—</span>
                          )}
                        </td>
                        <td className="admin-agent-key-cell">
                          {r.agentKey ? (
                            <>
                              <code className="admin-key" title={r.agentKey}>
                                {r.agentKey.slice(0, 8)}…
                              </code>
                              <button
                                type="button"
                                className="admin-btn admin-btn-ghost"
                                title="复制完整 AGENT_KEY（写入采集端配置）"
                                onClick={() => copyAgentKey(r.agentKey!)}
                              >
                                复制
                              </button>
                            </>
                          ) : (
                            <span className="admin-muted">—</span>
                          )}
                        </td>
                        <td>
                          {editId === r.id ? (
                            <input
                              type="checkbox"
                              checked={editForm.enabled}
                              onChange={(e) => setEditForm({ ...editForm, enabled: e.target.checked })}
                            />
                          ) : (
                            <span>{r.enabled ? '是' : '否'}</span>
                          )}
                        </td>
                        <td className="admin-actions">
                          {editId === r.id ? (
                            <>
                              <button type="button" className="admin-btn" onClick={() => void saveEdit()}>
                                保存
                              </button>
                              <button type="button" className="admin-btn" onClick={() => setEditId(null)}>
                                取消
                              </button>
                            </>
                          ) : (
                            <>
                              <button type="button" className="admin-btn" onClick={() => startEdit(r)}>
                                编辑
                              </button>
                              <button type="button" className="admin-btn danger" onClick={() => void remove(r.id)}>
                                删除
                              </button>
                            </>
                          )}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </>
        )}
      </div>
    </div>
  );
};
