import { useState, useEffect } from 'react';
import { Bell, Settings, User, Plus, Search, Home, FileText, CheckCircle, LogOut, PanelLeft, PanelLeftClose } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useAuth } from '@/contexts/AuthContext';
import royalEnfieldLogo from '@/assets/images/royal_enfield_logo.png';

interface PageLayoutProps {
  children: React.ReactNode;
  currentPage?: string;
  onNavigate?: (page: string) => void;
  onNewRequest?: () => void;
  onLogout?: () => void;
}

export function PageLayout({ children, currentPage = 'dashboard', onNavigate, onNewRequest, onLogout }: PageLayoutProps) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [showLogoutDialog, setShowLogoutDialog] = useState(false);
  const { user } = useAuth();
  
  // Get user initials for avatar
  const getUserInitials = () => {
    if (user?.displayName) {
      const names = user.displayName.split(' ').filter(Boolean);
      if (names.length >= 2) {
        return `${names[0]?.[0] || ''}${names[names.length - 1]?.[0] || ''}`.toUpperCase();
      }
      return user.displayName.substring(0, 2).toUpperCase();
    }
    if (user?.email) {
      return user.email.substring(0, 2).toUpperCase();
    }
    return 'U';
  };
  
  const menuItems = [
    { id: 'dashboard', label: 'Dashboard', icon: Home },
    { id: 'my-requests', label: 'My Requests', icon: User },
    { id: 'open-requests', label: 'Open Requests', icon: FileText },
    { id: 'closed-requests', label: 'Closed Requests', icon: CheckCircle },
  ];

  const toggleSidebar = () => {
    setSidebarOpen(!sidebarOpen);
  };

  // Handle responsive behavior: sidebar open on desktop, closed on mobile
  useEffect(() => {
    const handleResize = () => {
      // 768px is the md breakpoint in Tailwind
      if (window.innerWidth >= 768) {
        setSidebarOpen(true); // Always open on desktop
      } else {
        setSidebarOpen(false); // Closed by default on mobile
      }
    };

    // Set initial state
    handleResize();

    // Add event listener
    window.addEventListener('resize', handleResize);

    // Cleanup
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <div className="min-h-screen flex w-full bg-background">
      {/* Mobile Overlay */}
      {sidebarOpen && (
        <div 
          className="fixed inset-0 bg-black/50 z-40 md:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar - Hidden on mobile by default, toggleable on desktop */}
      <aside className={`
        fixed md:relative
        inset-y-0 left-0
        w-64
        transform transition-transform duration-300 ease-in-out
        ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}
        md:translate-x-0
        ${sidebarOpen ? 'md:w-64' : 'md:w-0 md:-translate-x-full'}
        z-50 md:z-auto
        flex-shrink-0
        border-r border-gray-800 bg-black
        flex flex-col
      `}>
        <div className="w-64 h-full flex flex-col overflow-hidden">
          <div className="p-4 border-b border-gray-800 flex-shrink-0">
            <div className="flex items-center gap-3">
              <img 
                src={royalEnfieldLogo} 
                alt="Royal Enfield Logo" 
                className="w-10 h-10 shrink-0 object-contain"
              />
              <div className="min-w-0 flex-1">
                <h2 className="text-base font-semibold text-white truncate">Royal Enfield</h2>
                <p className="text-sm text-gray-400 truncate">Approval Portal</p>
              </div>
            </div>
          </div>
          <div className="p-3 flex-1 overflow-y-auto">
            <div className="space-y-2">
              {menuItems.map((item) => (
                <button
                  key={item.id}
                  onClick={() => {
                    onNavigate?.(item.id);
                    // Close sidebar on mobile after navigation
                    if (window.innerWidth < 768) {
                      setSidebarOpen(false);
                    }
                  }}
                  className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${
                    currentPage === item.id
                      ? 'bg-re-green text-white font-medium'
                      : 'text-gray-300 hover:bg-gray-900 hover:text-white'
                  }`}
                >
                  <item.icon className="w-4 h-4 shrink-0" />
                  <span className="truncate">{item.label}</span>
                </button>
              ))}
              
              {/* Quick Action in Sidebar - Right below menu items */}
              <div className="mt-6">
                <Button
                  onClick={onNewRequest}
                  className="w-full bg-re-green hover:bg-re-green/90 text-white text-sm"
                  size="sm"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  Raise New Request
                </Button>
              </div>
            </div>
          </div>
        </div>
      </aside>

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Header */}
        <header className="h-16 border-b border-gray-200 bg-white flex items-center justify-between px-6 shrink-0">
          <div className="flex items-center gap-4 min-w-0 flex-1">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={toggleSidebar}
                      className="shrink-0 h-10 w-10 sidebar-toggle"
                    >
                      {sidebarOpen ? <PanelLeftClose className="w-5 h-5 text-gray-600" /> : <PanelLeft className="w-5 h-5 text-gray-600" />}
                    </Button>
            <div className="relative max-w-md flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                placeholder="Search..."
                className="pl-10 bg-white border-gray-300 hover:border-gray-400 focus:border-re-green focus:ring-1 focus:ring-re-green w-full text-sm h-10"
              />
            </div>
          </div>

          <div className="flex items-center gap-4 shrink-0">
            <Button
              onClick={onNewRequest}
              className="bg-re-green hover:bg-re-green/90 text-white gap-2 hidden md:flex text-sm"
              size="sm"
            >
              <Plus className="w-4 h-4" />
              New Request
            </Button>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="relative shrink-0 h-10 w-10">
                  <Bell className="w-5 h-5" />
                  <Badge className="absolute -top-1 -right-1 w-5 h-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center p-0">
                    3
                  </Badge>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-80">
                <div className="p-3 border-b">
                  <h4 className="font-semibold text-base">Notifications</h4>
                </div>
                <div className="p-3 space-y-2">
                  <div className="text-sm">
                    <p className="font-medium">RE-REQ-001 needs approval</p>
                    <p className="text-muted-foreground text-xs">SLA expires in 2 hours</p>
                  </div>
                  <div className="text-sm">
                    <p className="font-medium">New comment on RE-REQ-003</p>
                    <p className="text-muted-foreground text-xs">From John Doe - 5 min ago</p>
                  </div>
                </div>
              </DropdownMenuContent>
            </DropdownMenu>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Avatar className="cursor-pointer shrink-0 h-10 w-10">
                  <AvatarImage src={user?.picture || ''} />
                  <AvatarFallback className="bg-re-green text-white text-sm">
                    {getUserInitials()}
                  </AvatarFallback>
                </Avatar>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => onNavigate?.('profile')}>
                  <User className="w-4 h-4 mr-2" />
                  Profile
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => onNavigate?.('settings')}>
                  <Settings className="w-4 h-4 mr-2" />
                  Settings
                </DropdownMenuItem>
                <DropdownMenuItem 
                  onClick={() => setShowLogoutDialog(true)} 
                  className="text-red-600 focus:text-red-600"
                >
                  <LogOut className="w-4 h-4 mr-2" />
                  Logout
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </header>

        {/* Main Content */}
        <main className="flex-1 p-6 overflow-auto min-w-0">
          {children}
        </main>
      </div>

      {/* Logout Confirmation Dialog */}
      <AlertDialog open={showLogoutDialog} onOpenChange={setShowLogoutDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <LogOut className="w-5 h-5 text-red-600" />
              Confirm Logout
            </AlertDialogTitle>
            <AlertDialogDescription className="pt-2">
              Are you sure you want to logout? You will need to sign in again to access your account.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setShowLogoutDialog(false)}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={async () => {
                console.log('🔴 Logout button clicked in PageLayout');
                console.log('🔴 onLogout function exists?', !!onLogout);
                setShowLogoutDialog(false);
                if (onLogout) {
                  console.log('🔴 Calling onLogout function...');
                  try {
                    await onLogout();
                    console.log('🔴 onLogout completed');
                  } catch (error) {
                    console.error('🔴 Error calling onLogout:', error);
                  }
                } else {
                  console.error('🔴 ERROR: onLogout is undefined!');
                }
              }}
              className="bg-red-600 hover:bg-red-700 text-white focus:ring-red-600"
            >
              <LogOut className="w-4 h-4 mr-2" />
              Logout
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}