import { createContext, useContext, useState } from 'react';
import { NavLink, Outlet } from 'react-router-dom';

const TOKEN_KEY = 'bridzik_admin_token';

const AdminTokenContext = createContext<string>('');

/** Admin token, read from the input/sessionStorage owned by AdminLayout.
 *  Kept separate from the player login -- /admin is gated by ADMIN_TOKEN only. */
export function useAdminToken(): string {
  return useContext(AdminTokenContext);
}

export default function AdminLayout() {
  const [token, setToken] = useState(() => sessionStorage.getItem(TOKEN_KEY) ?? '');
  const [draft, setDraft] = useState('');

  if (!token) {
    return (
      <div className="max-w-sm mx-auto p-4 pt-24 min-h-screen">
        <h1 className="font-serif text-2xl text-gold mb-4">Admin</h1>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            if (!draft.trim()) return;
            sessionStorage.setItem(TOKEN_KEY, draft.trim());
            setToken(draft.trim());
          }}
          className="flex flex-col gap-3"
        >
          <input
            type="password"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="Admin token"
            className="bg-header border border-[#142018] rounded-lg px-3 py-2 text-green-score placeholder:text-green-dim outline-none focus:border-gold"
            autoFocus
          />
          <button
            type="submit"
            className="px-4 py-2 rounded-lg font-serif font-semibold bg-gold text-table hover:bg-gold-bright transition-colors"
          >
            Vstup
          </button>
        </form>
      </div>
    );
  }

  return (
    <AdminTokenContext.Provider value={token}>
      <div className="max-w-4xl mx-auto p-4 pt-8 min-h-screen">
        <div className="flex items-center justify-between mb-6">
          <h1 className="font-serif text-2xl text-gold">Admin</h1>
          <button
            onClick={() => {
              sessionStorage.removeItem(TOKEN_KEY);
              setToken('');
            }}
            className="text-sm text-green-dim hover:text-gold"
          >
            Odhlásiť
          </button>
        </div>
        <nav className="flex gap-4 mb-6 border-b border-gold/[.14] pb-2">
          <NavLink
            to="stats"
            className={({ isActive }) =>
              `text-sm ${isActive ? 'text-gold' : 'text-green-dim hover:text-gold'}`
            }
          >
            Štatistiky
          </NavLink>
        </nav>
        <Outlet />
      </div>
    </AdminTokenContext.Provider>
  );
}
