"use client";

import * as React from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { LogOut, User as UserIcon, Menu } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet";
import { AdminSidebarNav } from "./admin-sidebar";

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";

interface AdminHeaderProps {
  user: {
    id: string;
    name: string;
    email: string;
    level: "MAIN_ADMIN" | "SUB_ADMIN";
    role: string;
  };
  pendingResetRequestsCount?: number;
}

export function AdminHeader({ user, pendingResetRequestsCount = 0 }: AdminHeaderProps) {
  const router = useRouter();
  const [loggingOut, setLoggingOut] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [showLogoutConfirm, setShowLogoutConfirm] = React.useState(false);

  const handleLogout = async () => {
    try {
      setLoggingOut(true);
      await fetch("/api/admin/auth/logout", { method: "POST" });
      router.push("/admin/login");
      router.refresh();
    } catch {
      router.push("/admin/login");
    } finally {
      setLoggingOut(false);
      setShowLogoutConfirm(false);
    }
  };

  return (
    <header className="sticky top-0 z-30 flex h-16 w-full items-center justify-between border-b border-neutral-200 bg-white/95 px-4 sm:px-6 backdrop-blur-sm dark:border-neutral-800 dark:bg-neutral-900/95">
      <div className="flex items-center gap-3">
        {/* Mobile Sidebar Trigger (Sheet) */}
        <div className="md:hidden">
          <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
            <SheetTrigger asChild>
              <Button
                variant="ghost"
                size="sm"
                className="h-9 w-9 p-0 text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"
                aria-label="Open Navigation Menu"
              >
                <Menu className="h-5 w-5" />
              </Button>
            </SheetTrigger>
            <SheetContent side="left" className="w-72 p-0 bg-neutral-50 dark:bg-neutral-950">
              <SheetHeader className="border-b border-neutral-200 dark:border-neutral-800 p-4 text-left">
                <div className="flex items-center gap-2.5">
                  <div className="relative flex h-8 w-8 items-center justify-center overflow-hidden rounded-lg bg-neutral-100 dark:bg-neutral-800">
                    <Image
                      src="/images/quto-logo.webp"
                      alt="Quto AI"
                      width={28}
                      height={28}
                      className="object-contain"
                    />
                  </div>
                  <div>
                    <SheetTitle className="text-sm font-bold">Quto AI Admin</SheetTitle>
                    <span className="text-[10px] text-neutral-500 uppercase tracking-wider font-semibold">
                      Publishing & CMS
                    </span>
                  </div>
                </div>
              </SheetHeader>
              <AdminSidebarNav
                user={user}
                pendingResetRequestsCount={pendingResetRequestsCount}
                onNavigate={() => setMobileOpen(false)}
              />
            </SheetContent>
          </Sheet>
        </div>

        {/* Brand Logo & Name */}
        <Link href="/admin" className="flex items-center gap-2.5">
          <div className="relative flex h-8 w-8 items-center justify-center overflow-hidden rounded-lg bg-neutral-100 dark:bg-neutral-800">
            <Image
              src="/images/quto-logo.webp"
              alt="Quto AI"
              width={28}
              height={28}
              className="object-contain"
              priority
            />
          </div>
          <div className="flex flex-col">
            <span className="font-semibold text-sm tracking-tight text-neutral-900 dark:text-white">
              Quto AI
            </span>
            <span className="text-[10px] font-medium tracking-wider text-neutral-500 uppercase hidden sm:inline">
              Control Center
            </span>
          </div>
        </Link>
      </div>

      <div className="flex items-center gap-2.5 sm:gap-4">
        {/* User Pill */}
        <div className="flex items-center gap-2 rounded-full border border-neutral-200 bg-neutral-50 py-1 px-2.5 sm:py-1.5 sm:pr-3 sm:pl-2.5 dark:border-neutral-800 dark:bg-neutral-950">
          <div className="flex h-6 w-6 items-center justify-center rounded-full bg-neutral-900 text-white dark:bg-white dark:text-neutral-900 shrink-0">
            <UserIcon className="h-3.5 w-3.5" />
          </div>
          <div className="flex flex-col text-left max-w-[120px] sm:max-w-[180px]">
            <div className="flex items-center gap-1.5">
              <span className="text-xs font-semibold text-neutral-900 dark:text-white truncate">
                {user.name}
              </span>
              <span
                className={`rounded-full px-1.5 py-0.2 text-[8px] sm:text-[9px] font-bold tracking-wider uppercase hidden xs:inline ${
                  user.level === "MAIN_ADMIN"
                    ? "bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"
                    : "bg-neutral-200 text-neutral-800 dark:bg-neutral-800 dark:text-neutral-200"
                }`}
              >
                {(user.level === "MAIN_ADMIN" ? "MAIN ADMIN" : (user.role || "SUB_ADMIN")).replace(/_/g, " ")}
              </span>
            </div>
            <span className="text-[10px] text-neutral-500 truncate hidden sm:inline">{user.email}</span>
          </div>
        </div>

        {/* Logout Confirmation Dialog */}
        <AlertDialog open={showLogoutConfirm} onOpenChange={setShowLogoutConfirm}>
          <AlertDialogTrigger asChild>
            <Button
              variant="outline"
              size="sm"
              className="h-9 gap-1.5 text-xs text-neutral-700 dark:text-neutral-300"
              title="Sign out of admin session"
            >
              <LogOut className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">Sign Out</span>
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Are you sure you want to log out?</AlertDialogTitle>
              <AlertDialogDescription>
                Your active session will be securely ended. You will need to enter your credentials or PIN to sign back in.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={loggingOut}>Cancel</AlertDialogCancel>
              <AlertDialogAction
                onClick={(e) => {
                  e.preventDefault();
                  handleLogout();
                }}
                disabled={loggingOut}
              >
                {loggingOut ? "Signing out..." : "Log Out"}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </header>
  );
}
