/**
 * Trouve-KA — page admin (porte à jeton + dashboard)
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 */

"use client";

import { useCallback, useEffect, useState } from "react";
import { AdminDashboard } from "@/components/admin/dashboard";
import { TokenForm } from "@/components/admin/token-form";
import { ADMIN_TOKEN_KEY } from "@/lib/admin";

export default function AdminPage() {
  // undefined = lecture de sessionStorage en cours; null = pas de jeton.
  const [token, setToken] = useState<string | null | undefined>(undefined);
  const [expired, setExpired] = useState(false);

  useEffect(() => {
    setToken(sessionStorage.getItem(ADMIN_TOKEN_KEY));
  }, []);

  const handleUnauthorized = useCallback(() => {
    sessionStorage.removeItem(ADMIN_TOKEN_KEY);
    setExpired(true);
    setToken(null);
  }, []);

  const handleToken = useCallback((value: string) => {
    sessionStorage.setItem(ADMIN_TOKEN_KEY, value);
    setExpired(false);
    setToken(value);
  }, []);

  const handleLogout = useCallback(() => {
    sessionStorage.removeItem(ADMIN_TOKEN_KEY);
    setExpired(false);
    setToken(null);
  }, []);

  if (token === undefined) {
    return null;
  }

  if (!token) {
    return <TokenForm onSubmit={handleToken} expired={expired} />;
  }

  return (
    <AdminDashboard
      token={token}
      onUnauthorized={handleUnauthorized}
      onLogout={handleLogout}
    />
  );
}
