import { useState, useCallback, useEffect } from 'react';
import { getGroups, addGroup, updateGroup, deleteGroup } from '../services/api';
import { GROUPS_CHANGED_EVENT } from '../constants/events';

function notifyGroupsChanged() {
  window.dispatchEvent(new CustomEvent(GROUPS_CHANGED_EVENT));
}

export default function AdminGroupsPanel() {
  const [groups, setGroups] = useState(null);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState('');
  const [newName, setNewName] = useState('');
  const [adding, setAdding] = useState(false);

  const [editingId, setEditingId] = useState(null);
  const [editName, setEditName] = useState('');
  const [saveBusy, setSaveBusy] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setErr('');
    try {
      const data = await getGroups();
      setGroups(data || []);
    } catch (e) {
      setErr(e.message || '加载分类失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function handleAdd(e) {
    e.preventDefault();
    const name = newName.trim();
    if (!name) return;
    setAdding(true);
    setErr('');
    try {
      await addGroup(name);
      setNewName('');
      await load();
      notifyGroupsChanged();
    } catch (e) {
      setErr(e.message || '添加失败');
    } finally {
      setAdding(false);
    }
  }

  function startEdit(g) {
    setEditingId(g.id);
    setEditName(g.name);
  }

  function cancelEdit() {
    setEditingId(null);
    setEditName('');
  }

  async function handleSaveEdit(e) {
    e.preventDefault();
    if (!editingId) return;
    const name = editName.trim();
    if (!name) return;
    setSaveBusy(true);
    setErr('');
    try {
      await updateGroup(editingId, { name });
      cancelEdit();
      await load();
      notifyGroupsChanged();
    } catch (e) {
      setErr(e.message || '保存失败');
    } finally {
      setSaveBusy(false);
    }
  }

  async function handleDelete(g) {
    if (!confirm(`确定删除分类「${g.name}」？\n使用该分类的站点将自动归入其他分类。`)) {
      return;
    }
    setErr('');
    try {
      await deleteGroup(g.id);
      await load();
      notifyGroupsChanged();
    } catch (e) {
      setErr(e.message || '删除失败');
    }
  }

  return (
    <section className="bg-white/90 backdrop-blur border border-emerald-100 rounded-xl shadow-sm p-4 sm:p-5">
      <h2 className="text-sm font-semibold text-gray-800 mb-1">网站分类</h2>
      <p className="text-xs text-gray-500 mb-4">
        增删改分类后，列表与筛选会同步更新；删除分类时，原归属站点会合并到剩余的第一个分类。
      </p>

      <form onSubmit={handleAdd} className="flex flex-col sm:flex-row gap-2 mb-4">
        <input
          type="text"
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          placeholder="新分类名称"
          className="flex-1 px-3 py-2 rounded-lg border border-gray-200 text-sm focus:ring-2 focus:ring-emerald-500 outline-none"
        />
        <button
          type="submit"
          disabled={adding || !newName.trim()}
          className="px-4 py-2 text-sm font-medium text-white bg-emerald-600 rounded-lg hover:bg-emerald-700 disabled:opacity-50"
        >
          {adding ? '添加中…' : '添加分类'}
        </button>
      </form>

      {loading && !groups ? (
        <p className="text-sm text-gray-500">加载中…</p>
      ) : (
        <ul className="divide-y divide-gray-100 border border-gray-100 rounded-lg overflow-hidden">
          {(groups || []).map((g) => (
            <li key={g.id} className="flex flex-col sm:flex-row sm:items-center gap-2 px-3 py-2.5 bg-white text-sm">
              {editingId === g.id ? (
                <form onSubmit={handleSaveEdit} className="flex flex-1 flex-wrap items-center gap-2">
                  <input
                    value={editName}
                    onChange={(e) => setEditName(e.target.value)}
                    className="flex-1 min-w-[8rem] px-2 py-1.5 rounded border border-gray-200 text-sm"
                    autoFocus
                  />
                  <button
                    type="submit"
                    disabled={saveBusy || !editName.trim()}
                    className="text-xs px-2 py-1 rounded bg-emerald-600 text-white disabled:opacity-50"
                  >
                    保存
                  </button>
                  <button type="button" onClick={cancelEdit} className="text-xs px-2 py-1 rounded border border-gray-200">
                    取消
                  </button>
                </form>
              ) : (
                <>
                  <div className="flex-1 min-w-0">
                    <span className="font-medium text-gray-800">{g.name}</span>
                    <code className="ml-2 text-[10px] text-gray-400 font-mono">{g.id}</code>
                  </div>
                  <div className="flex gap-1.5">
                    <button
                      type="button"
                      onClick={() => startEdit(g)}
                      className="text-xs px-2 py-1 rounded border border-gray-200 text-gray-700 hover:bg-gray-50"
                    >
                      编辑
                    </button>
                    <button
                      type="button"
                      onClick={() => handleDelete(g)}
                      className="text-xs px-2 py-1 rounded border border-red-100 text-red-600 hover:bg-red-50"
                    >
                      删除
                    </button>
                  </div>
                </>
              )}
            </li>
          ))}
        </ul>
      )}

      {err ? <p className="text-xs text-red-600 mt-3">{err}</p> : null}
    </section>
  );
}
