
"use client";

import { LayoutGrid, Boxes, Timer, Calculator, FileText, Menu, LogIn, LogOut as LogOutIcon, UserCircle, ShieldAlert, Printer, Loader2, Briefcase, Home, ListFilter, CalendarDays, BarChartHorizontalBig, CalendarCheck } from 'lucide-react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import React, { useState, useEffect } from 'react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
  DropdownMenuLabel,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
  DropdownMenuPortal
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { useAuth } from '@/contexts/AuthContext';
import { Skeleton } from '@/components/ui/skeleton';
import type { CountInfo } from '@/types';

export function SiteHeader() {
  const { user, isAuthenticated, isLoading, logout, login } = useAuth();
  const [clientName, setClientName] = useState('');
  const [siteName, setSiteName] = useState('');

  useEffect(() => {
    const loadCountInfo = () => {
      if (typeof window !== 'undefined') {
        try {
          const storedInfo = localStorage.getItem('countToolHubInfo');
          if (storedInfo) {
            const parsedInfo: CountInfo = JSON.parse(storedInfo);
            setClientName(parsedInfo.clientName || '');
            setSiteName(parsedInfo.siteName || '');
          } else {
            setClientName('');
            setSiteName('');
          }
        } catch (error) {
          console.error("Error loading count info for header:", error);
          setClientName('');
          setSiteName('');
        }
      }
    };

    loadCountInfo();

    const handleStorageChange = (event: StorageEvent) => {
      if (event.key === 'countToolHubInfo' || event.key === null) {
        loadCountInfo();
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  const navLinks = [
    { href: "/breakdown", label: "Breakdown", icon: <Boxes />, contractsHidden: true },
    { href: "/tasktimer", label: "Finish Estimator", icon: <Timer /> },
    { href: "/scan-check-calculator", label: "Scan Accuracy", icon: <Calculator /> },
    { href: "/count-error-tracker", label: "Count Error Tracker", icon: <ShieldAlert /> },
    { href: "/report", label: "Count Report", icon: <Printer /> },
    {
      label: "Tesco Client Data",
      icon: <Briefcase />,
      adminOnly: true,
      subItems: [
        { href: "/tesco-client-data", label: "Hub", icon: <Home /> },
        { href: "/tesco-client-data/store-directory", label: "Store Directory", icon: <ListFilter /> },
        { href: "/tesco-client-data/am-exec-info", label: "AM Exec Info", icon: <CalendarDays /> },
        { href: "/tesco-client-data/expected-units", label: "Expected Units", icon: <BarChartHorizontalBig /> },
        { href: "/tesco-client-data/count-plans", label: "Count Plans", icon: <CalendarCheck /> },
      ]
    },
  ];

  // Skeleton for the entire header if real auth is loading
  if (isLoading && !isAuthenticated) {
    return (
      <header className="sticky top-0 z-50 w-full border-b-2 border-yellow-400 bg-primary text-primary-foreground print:hidden px-1">
        <nav className="container mx-auto px-4 sm:px-6 lg:px-8 flex items-center justify-between h-auto py-3">
          <div className="flex flex-col">
            <Skeleton className="h-6 w-48 bg-primary-foreground/20" />
            <Skeleton className="h-3 w-32 mt-1 bg-primary-foreground/20" />
          </div>
          <div className="flex items-center space-x-2">
            <Skeleton className="h-8 w-8 rounded-full bg-primary-foreground/20" />
            <Skeleton className="h-8 w-24 bg-primary-foreground/20" />
          </div>
        </nav>
      </header>
    );
  }

  return (
    <header className="sticky top-0 z-50 w-full border-b-2 border-yellow-400 bg-primary text-primary-foreground print:hidden px-1">
      <nav className="container mx-auto px-4 sm:px-6 lg:px-8 flex items-center justify-between h-auto py-3">
        <div className="flex flex-col">
          <Link href="/" className="flex items-center space-x-2">
            <LayoutGrid className="h-[25px] w-auto" />
            <span className="text-xl font-semibold">Count Tool Hub</span>
          </Link>
          <p className="text-xs text-primary-foreground/80 mt-0.5">
            Your central application portal.
          </p>
        </div>

        <div className="flex items-center space-x-2">
          {(clientName || siteName) && (
            <div className="hidden md:flex flex-col text-left text-xs border-l border-primary-foreground/30 pl-2 ml-2">
              {clientName && <span className="font-medium truncate max-w-[150px]" title={clientName}>{clientName}</span>}
              {siteName && <span className="text-primary-foreground/80 truncate max-w-[150px]" title={siteName}>{siteName}</span>}
            </div>
          )}

          {isAuthenticated && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="text-primary-foreground hover:bg-primary/80 hover:text-primary-foreground focus-visible:ring-yellow-400">
                  <Menu className="h-5 w-5" />
                  <span className="sr-only">Open navigation menu</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                {navLinks.map(link => {
                  if (link.contractsHidden && user?.role === 'contracts') {
                    return null;
                  }
                  if (link.adminOnly && user?.role !== 'admin') {
                    return null;
                  }

                  if (link.subItems && user?.role === 'admin') {
                    return (
                      <DropdownMenuSub key={link.label}>
                        <DropdownMenuSubTrigger>
                          {React.cloneElement(link.icon, { className: "mr-2 h-4 w-4" })}
                          <span>{link.label}</span>
                        </DropdownMenuSubTrigger>
                        <DropdownMenuPortal>
                          <DropdownMenuSubContent>
                            {link.subItems.map(subItem => (
                              <DropdownMenuItem key={subItem.href} asChild className="cursor-pointer">
                                <Link href={subItem.href} className="flex items-center w-full">
                                  {React.cloneElement(subItem.icon, { className: "mr-2 h-4 w-4" })}
                                  {subItem.label}
                                </Link>
                              </DropdownMenuItem>
                            ))}
                          </DropdownMenuSubContent>
                        </DropdownMenuPortal>
                      </DropdownMenuSub>
                    );
                  }

                  return (
                    <DropdownMenuItem key={link.href || link.label} asChild className="cursor-pointer">
                      <Link href={link.href!} className="flex items-center w-full">
                        {React.cloneElement(link.icon, { className: "mr-2 h-4 w-4" })}
                        {link.label}
                      </Link>
                    </DropdownMenuItem>
                  );
                })}
              </DropdownMenuContent>
            </DropdownMenu>
          )}

          {isAuthenticated && user ? (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="text-primary-foreground hover:bg-primary/80 hover:text-primary-foreground focus-visible:ring-yellow-400 px-2 md:px-3 text-xs md:text-sm h-auto py-1">
                  {user.photo ? (
                    <Avatar className="h-6 w-6 mr-1 md:mr-2 border-2 border-primary-foreground/50">
                      <AvatarImage src={user.photo} alt={user.name || user.email} />
                      <AvatarFallback>
                        <UserCircle className="h-5 w-5" />
                      </AvatarFallback>
                    </Avatar>
                  ) : (
                    <UserCircle className="h-6 w-6 mr-1 md:mr-2" />
                  )}
                  <span className="truncate max-w-[100px] sm:max-w-[150px]">{user.name || user.email}</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel className="font-semibold truncate max-w-[200px]">
                  {user.name || user.email}
                </DropdownMenuLabel>
                <DropdownMenuItem disabled className="text-xs text-muted-foreground opacity-70">
                   Role: {user.role}
                 </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={logout} className="cursor-pointer text-destructive focus:text-destructive focus:bg-destructive/10">
                  <LogOutIcon className="mr-2 h-4 w-4" />
                  Logout
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          ) : (isLoading && !isAuthenticated) ? (
            <Skeleton className="h-8 w-24 bg-primary-foreground/20" />
          ) : (
            <Button onClick={login} variant="ghost" className="text-primary-foreground hover:bg-primary/80 hover:text-primary-foreground focus-visible:ring-yellow-400 px-2 md:px-3 text-xs md:text-sm h-auto py-1">
              <LogIn className="mr-1 md:mr-2 h-4 w-4" />
              Login
            </Button>
          )}
        </div>
      </nav>
    </header>
  );
}
