import React, { useCallback, useEffect, useState } from 'react';
import {
  addIgnoreFolder,
  deleteIgnoreFolder,
  fetchIgnoreList,
  updateIgnoreFolder,
} from '../utils/fileUtils';
import { useAdmin } from '../context/AdminContext';
import './AdminPanel.css';

export default function AdminPanel() {
  const {
    adminPanelOpen,
    closeAdminPanel,
    logoutAdmin,
    getStoredToken,
    notifyIgnoreListChanged,
  } = useAdmin();
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [newName, setNewName] = useState('');
  const [editing, setEditing] = useState(null);
  const [editValue, setEditValue] = useState('');

  const load = useCallback(async () => {
    const token = getStoredToken();
    if (!token) {
      setError('未登录');
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const data = await fetchIgnoreList(token);
      setItems(data.ignore || []);
    } catch (e) {
      setError(e.message || '加载失败');
      setItems([]);
    } finally {
      setLoading(false);
    }
  }, [getStoredToken]);

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

  if (!adminPanelOpen) {
    return null;
  }

  const token = getStoredToken();

  const handleAdd = async (e) => {
    e.preventDefault();
    const name = newName.trim();
    if (!name || !token) return;
    setError(null);
    try {
      const data = await addIgnoreFolder(token, name);
      setItems(data.ignore || []);
      setNewName('');
      notifyIgnoreListChanged();
    } catch (err) {
      setError(err.message || '添加失败');
    }
  };

  const handleDelete = async (name) => {
    if (!token || !window.confirm(`确定从忽略列表中移除「${name}」？`)) return;
    setError(null);
    try {
      const data = await deleteIgnoreFolder(token, name);
      setItems(data.ignore || []);
      notifyIgnoreListChanged();
    } catch (err) {
      setError(err.message || '删除失败');
    }
  };

  const startEdit = (name) => {
    setEditing(name);
    setEditValue(name);
  };

  const cancelEdit = () => {
    setEditing(null);
    setEditValue('');
  };

  const saveEdit = async () => {
    if (!token || editing == null) return;
    const next = editValue.trim();
    if (!next || next === editing) {
      cancelEdit();
      return;
    }
    setError(null);
    try {
      const data = await updateIgnoreFolder(token, editing, next);
      setItems(data.ignore || []);
      cancelEdit();
      notifyIgnoreListChanged();
    } catch (err) {
      setError(err.message || '保存失败');
    }
  };

  return (
    <div
      className="admin-panel-backdrop"
      role="presentation"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) closeAdminPanel();
      }}
    >
      <div
        className="admin-panel"
        role="dialog"
        aria-modal="true"
        aria-labelledby="admin-panel-title"
        onMouseDown={(e) => e.stopPropagation()}
      >
        <div className="admin-panel-header">
          <h2 id="admin-panel-title" className="admin-panel-title">
            后台 · 忽略的笔记文件夹
          </h2>
          <div className="admin-panel-header-actions">
            <button type="button" className="admin-panel-text-btn" onClick={logoutAdmin}>
              退出登录
            </button>
            <button type="button" className="admin-panel-close" onClick={closeAdminPanel} aria-label="关闭">
              ×
            </button>
          </div>
        </div>

        <p className="admin-panel-desc">
          以下名称与笔记根目录下的一级文件夹名匹配；匹配的文件夹不会出现在公开目录树中。
        </p>

        <form className="admin-panel-add" onSubmit={handleAdd}>
          <input
            type="text"
            className="admin-panel-input"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="添加文件夹名称"
            aria-label="新忽略文件夹名"
          />
          <button type="submit" className="admin-panel-btn primary" disabled={!newName.trim()}>
            添加
          </button>
        </form>

        {error && (
          <p className="admin-panel-error" role="alert">
            {error}
          </p>
        )}

        <div className="admin-panel-list-wrap">
          {loading && <p className="admin-panel-muted">加载中…</p>}
          {!loading && items.length === 0 && !error && (
            <p className="admin-panel-muted">暂无忽略项，可在上方添加。</p>
          )}
          <ul className="admin-panel-list">
            {items.map((name) => (
              <li key={name} className="admin-panel-row">
                {editing === name ? (
                  <>
                    <input
                      type="text"
                      className="admin-panel-input inline"
                      value={editValue}
                      onChange={(e) => setEditValue(e.target.value)}
                      aria-label="编辑名称"
                    />
                    <button type="button" className="admin-panel-btn small" onClick={saveEdit}>
                      保存
                    </button>
                    <button type="button" className="admin-panel-btn small secondary" onClick={cancelEdit}>
                      取消
                    </button>
                  </>
                ) : (
                  <>
                    <span className="admin-panel-name">{name}</span>
                    <button type="button" className="admin-panel-btn small secondary" onClick={() => startEdit(name)}>
                      编辑
                    </button>
                    <button type="button" className="admin-panel-btn small danger" onClick={() => handleDelete(name)}>
                      删除
                    </button>
                  </>
                )}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
}
