import { Link, Outlet, redirect } from "react-router";
import { getAuth } from "@clerk/react-router/server";
import type { Route } from "./+types/admin";

import { isUserAdminByClerkId } from "~/models/user";
import { Button } from "~/components/ui/button";
import {
  LayoutDashboard,
  Trophy,
  Calendar,
  FolderKanban,
  RefreshCw,
} from "lucide-react";

export function meta(): Route.MetaDescriptors {
  return [{ title: "Admin - Brackt" }];
}

export async function loader(args: Route.LoaderArgs) {
  const { userId } = await getAuth(args);

  if (!userId) {
    throw redirect("/");
  }

  const isAdmin = await isUserAdminByClerkId(userId);
  if (!isAdmin) {
    throw redirect("/");
  }

  return { isAdmin };
}

export default function AdminLayout() {
  return (
    <div className="flex min-h-screen">
      {/* Sidebar */}
      <aside className="w-64 border-r bg-muted/40">
        <div className="flex h-16 items-center border-b px-6">
          <h2 className="text-lg font-semibold">Admin Panel</h2>
        </div>
        <nav className="space-y-1 p-4">
          <Button variant="ghost" className="w-full justify-start" asChild>
            <Link to="/admin">
              <LayoutDashboard className="mr-2 h-4 w-4" />
              Dashboard
            </Link>
          </Button>
          <Button variant="ghost" className="w-full justify-start" asChild>
            <Link to="/admin/sports">
              <Trophy className="mr-2 h-4 w-4" />
              Sports
            </Link>
          </Button>
          <Button variant="ghost" className="w-full justify-start" asChild>
            <Link to="/admin/sports-seasons">
              <Calendar className="mr-2 h-4 w-4" />
              Sports Seasons
            </Link>
          </Button>
          <Button variant="ghost" className="w-full justify-start" asChild>
            <Link to="/admin/templates">
              <FolderKanban className="mr-2 h-4 w-4" />
              Season Templates
            </Link>
          </Button>
          <div className="border-t my-2" />
          <Button variant="ghost" className="w-full justify-start" asChild>
            <Link to="/admin/data-sync">
              <RefreshCw className="mr-2 h-4 w-4" />
              Data Sync
            </Link>
          </Button>
        </nav>
      </aside>

      {/* Main Content */}
      <main className="flex-1">
        <Outlet />
      </main>
    </div>
  );
}
