"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Loader2, LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { FileUploader } from "@/components/file-uploader";
import { FileList } from "@/components/file-list";
import { PersonaEditor } from "@/components/persona-editor";

export default function AdminPage() {
  const router = useRouter();
  const [checking, setChecking] = useState(true);
  const [refreshKey, setRefreshKey] = useState(0);

  useEffect(() => {
    (async () => {
      const r = await fetch("/api/admin/me", { credentials: "same-origin" });
      const session = r.ok ? await r.json().catch(() => null) : null;
      if (!session?.authenticated) router.replace("/admin/login");
      else setChecking(false);
    })();
  }, [router]);

  async function logout() {
    await fetch("/api/admin/logout", { method: "POST", credentials: "same-origin" });
    router.replace("/admin/login");
  }

  if (checking) {
    return (
      <div className="flex h-full items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <main className="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
      <header className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold tracking-tight">Educator Dashboard</h1>
          <p className="text-sm text-muted-foreground">
            Upload PDFs to your linked Hugging Face Dataset.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Link
            href="/"
            className="text-sm text-muted-foreground underline-offset-4 hover:underline"
          >
            ← Chat
          </Link>
          <Button variant="ghost" size="sm" onClick={logout}>
            <LogOut className="mr-1 h-4 w-4" /> Logout
          </Button>
        </div>
      </header>

      <Card>
        <CardHeader>
          <CardTitle>Upload PDFs</CardTitle>
        </CardHeader>
        <CardContent>
          <FileUploader onUploaded={() => setRefreshKey((k) => k + 1)} />
        </CardContent>
      </Card>

      <Card>
        <CardContent className="pt-6">
          <FileList refreshKey={refreshKey} />
        </CardContent>
      </Card>

      <Card>
        <CardContent className="pt-6">
          <PersonaEditor />
        </CardContent>
      </Card>
    </main>
  );
}
