"use client";

import { useState, useEffect } from "react";
import dynamic from "next/dynamic";

// Dynamically import admin components to reduce initial bundle size
const AdminDashboard = dynamic(() => import("@/components/AdminDashboard").then(mod => ({ default: mod.AdminDashboard })), {
  loading: () => <div className="flex min-h-screen items-center justify-center"><div className="text-lg">Loading...</div></div>,
  ssr: false,
});

const AdminLogin = dynamic(() => import("@/components/AdminLogin").then(mod => ({ default: mod.AdminLogin })), {
  loading: () => <div className="flex min-h-screen items-center justify-center"><div className="text-lg">Loading...</div></div>,
  ssr: false,
});

export default function AdminPage() {
  const [authenticated, setAuthenticated] = useState<boolean | null>(null);

  useEffect(() => {
    checkAuth();
  }, []);

  const checkAuth = async () => {
    try {
      const res = await fetch("/api/admin/check-auth");
      if (res.ok) {
        const data = await res.json();
        setAuthenticated(data.authenticated);
      } else {
        setAuthenticated(false);
      }
    } catch (error) {
      setAuthenticated(false);
    }
  };

  const handleLogin = async (username: string, password: string) => {
    try {
      const res = await fetch("/api/admin/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });

      if (res.ok) {
        setAuthenticated(true);
      } else {
        alert("Invalid credentials");
      }
    } catch (error) {
      alert("Login failed");
    }
  };

  const handleLogout = async () => {
    try {
      await fetch("/api/admin/logout", { method: "POST" });
      setAuthenticated(false);
    } catch (error) {
      console.error("Logout failed");
    }
  };

  if (authenticated === null) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <div className="text-lg">Loading...</div>
      </div>
    );
  }

  if (!authenticated) {
    return <AdminLogin onLogin={handleLogin} />;
  }

  return <AdminDashboard onLogout={handleLogout} />;
}

