import { useCallback, useEffect, useMemo, useState } from 'react';
import { api } from '../api';

export default function AdminCategories() {
  const [categories, setCategories] = useState([]);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [query, setQuery] = useState('');
  const [name, setName] = useState('');
  const [editingId, setEditingId] = useState(null);
  const [editName, setEditName] = useState('');
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    const data = await api.adminCategories();
    setCategories(data.categories || []);
  }, []);

  useEffect(() => {
    load().catch((err) => setError(err.message));
  }, [load]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return categories;
    return categories.filter((c) => c.name.toLowerCase().includes(q));
  }, [categories, query]);

  return (
    <div>
      <div className="section-head">
        <div>
          <h1>Categories</h1>
          <p className="muted">
            {categories.length} categories · rename updates items · delete only when empty
          </p>
        </div>
        <input
          className="admin-search"
          placeholder="Search categories…"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
      </div>

      {error && <div className="error">{error}</div>}
      {message && <div className="ok-msg">{message}</div>}

      <div className="admin-block">
        <h3>Create category</h3>
        <form
          className="form admin-row"
          onSubmit={async (e) => {
            e.preventDefault();
            setError('');
            setMessage('');
            setBusy(true);
            try {
              await api.createCategory({ name });
              setName('');
              setMessage('Category created.');
              await load();
            } catch (err) {
              setError(err.message);
            } finally {
              setBusy(false);
            }
          }}
        >
          <label>
            Name
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. Rifle, Charm…"
              required
            />
          </label>
          <button className="btn" type="submit" disabled={busy || !name.trim()}>
            {busy ? 'Creating…' : 'Create'}
          </button>
        </form>
      </div>

      <div className="admin-block">
        <h3>All categories</h3>
        {filtered.length === 0 ? (
          <p className="muted">No categories match.</p>
        ) : (
          <ul className="admin-cat-list">
            {filtered.map((cat) => (
              <li key={cat.id} className="admin-cat-row">
                {editingId === cat.id ? (
                  <form
                    className="admin-row admin-cat-edit"
                    onSubmit={async (e) => {
                      e.preventDefault();
                      setError('');
                      setMessage('');
                      setBusy(true);
                      try {
                        await api.updateCategory(cat.id, { name: editName });
                        setEditingId(null);
                        setEditName('');
                        setMessage('Category renamed.');
                        await load();
                      } catch (err) {
                        setError(err.message);
                      } finally {
                        setBusy(false);
                      }
                    }}
                  >
                    <input
                      value={editName}
                      onChange={(e) => setEditName(e.target.value)}
                      required
                      autoFocus
                    />
                    <button className="btn" type="submit" disabled={busy}>
                      Save
                    </button>
                    <button
                      type="button"
                      className="btn ghost"
                      onClick={() => {
                        setEditingId(null);
                        setEditName('');
                      }}
                    >
                      Cancel
                    </button>
                  </form>
                ) : (
                  <>
                    <div className="admin-row-main">
                      <strong>{cat.name}</strong>
                      <span className="muted">
                        {cat.itemCount} item{cat.itemCount === 1 ? '' : 's'}
                      </span>
                    </div>
                    <div className="admin-row">
                      <button
                        type="button"
                        className="btn secondary"
                        onClick={() => {
                          setEditingId(cat.id);
                          setEditName(cat.name);
                          setError('');
                          setMessage('');
                        }}
                      >
                        Rename
                      </button>
                      <button
                        type="button"
                        className="btn ghost"
                        disabled={cat.itemCount > 0 || busy}
                        title={
                          cat.itemCount > 0
                            ? `Used by ${cat.itemCount} item${cat.itemCount === 1 ? '' : 's'}`
                            : 'Delete category'
                        }
                        onClick={async () => {
                          if (cat.itemCount > 0) return;
                          setError('');
                          setMessage('');
                          setBusy(true);
                          try {
                            await api.deleteCategory(cat.id);
                            setMessage(`Deleted “${cat.name}”.`);
                            await load();
                          } catch (err) {
                            setError(err.message);
                          } finally {
                            setBusy(false);
                          }
                        }}
                      >
                        Delete
                      </button>
                    </div>
                  </>
                )}
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
