
'use client';

import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { Button } from '@/components/ui/button';
import { Menu, Search, Bell, Settings, PanelLeft, Building } from 'lucide-react';
import { SidebarNav } from '@/components/sidebar-nav';
import type { User, BookingResult, ParcelFormValues } from '@/lib/types';
import { usePathname } from 'next/navigation';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuItem } from '@/components/ui/dropdown-menu';
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
import Link from 'next/link';
import { useSidebar } from './ui/sidebar';
import React from 'react';
import { GlobalSearch } from './global-search';

export function Header({
  user,
  onBookingComplete,
  bookParcelAction,
}: {
  user: User;
  onBookingComplete: (result: BookingResult) => void;
  bookParcelAction?: (values: ParcelFormValues) => Promise<BookingResult>;
}) {
  const pathname = usePathname();
  const { toggleSidebar } = useSidebar();
  
  const getPageTitle = React.useCallback(() => {
    if (user.role === 'super-admin' || user.role === 'admin') {
      if (pathname === '/admin') return 'Admin Panel';
    } else {
        if (pathname === '/dashboard') return 'Seller Panel';
    }

    const segments = pathname.split('/').filter(Boolean);
    if (segments.length > 0) {
        const lastSegment = segments[segments.length - 1];
        if (lastSegment.startsWith('[') && lastSegment.endsWith(']')) {
             if (segments.length > 1) {
                const parentSegment = segments[segments.length - 2];
                // Capitalize and remove plural 's'
                const singularParent = parentSegment.endsWith('s') ? parentSegment.slice(0, -1) : parentSegment;
                return `${singularParent.charAt(0).toUpperCase() + singularParent.slice(1).replace(/-/g, ' ')} Detail`;
             }
        }
        return lastSegment.charAt(0).toUpperCase() + lastSegment.slice(1).replace(/-/g, ' ');
    }
    
    return 'Dashboard';
  }, [pathname, user.role]);

  const handleLogout = () => {
    window.location.href = '/login';
  };

  const pageTitle = getPageTitle();

  return (
    <header className="sticky top-0 z-30 flex h-16 items-center gap-4 border-b bg-card px-4 sm:px-6">
       <div className="lg:hidden">
        <Sheet>
            <SheetTrigger asChild>
            <Button variant="outline" size="icon" className="shrink-0">
                <Menu className="h-5 w-5" />
                <span className="sr-only">Toggle navigation menu</span>
            </Button>
            </SheetTrigger>
            <SheetContent side="left" className="flex flex-col p-0">
            <SidebarNav user={user} />
            </SheetContent>
        </Sheet>
       </div>
       <Button variant="ghost" size="icon" className="hidden lg:flex" onClick={toggleSidebar}>
            <PanelLeft className="h-5 w-5" />
            <span className="sr-only">Toggle Sidebar</span>
       </Button>

      <div className="flex-1">
        <h1 className="text-xl font-semibold">{pageTitle}</h1>
      </div>

      <div className="flex items-center gap-2 md:gap-4">
         {user.role === 'super-admin' && (
            <GlobalSearch />
         )}

         <Button variant="ghost" size="icon">
            <Bell className="h-5 w-5" />
            <span className="sr-only">Notifications</span>
          </Button>

         <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="relative h-10 w-10 rounded-full">
                    <Avatar className="h-10 w-10">
                        <AvatarImage src={user.avatar} alt={user.name} />
                        <AvatarFallback>{user.name.charAt(0)}</AvatarFallback>
                    </Avatar>
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-56" align="end" forceMount>
                <DropdownMenuLabel className="font-normal">
                <div className="flex flex-col space-y-1">
                    <p className="text-sm font-medium leading-none">{user.name}</p>
                    <p className="text-xs leading-none text-muted-foreground">
                    {user.email}
                    </p>
                </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem asChild>
                    <Link href={user.role === 'admin' || user.role === 'super-admin' ? '/admin/settings' : '/settings'}>
                        <Settings className="mr-2 h-4 w-4" />
                        <span>Settings</span>
                    </Link>
                </DropdownMenuItem>
                <DropdownMenuItem onClick={handleLogout}>Log out</DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  );
}
