import { ReactNode, useState, useRef, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useAuth } from '@/contexts/AuthContext';
import { useAbility } from '@/contexts/AbilityContext';
import { Action } from '@/lib/abilities';
import { api } from '@/lib/api';
import {
  Plane,
  Users,
  Car,
  Truck,
  Calendar,
  UserCog,
  LayoutDashboard,
  Settings,
  Radio,
  Menu,
  X,
  ChevronDown,
  Shield,
  LogOut,
  Phone,
  AlertCircle,
} from 'lucide-react';
import { UserMenu } from '@/components/UserMenu';
import { AppearanceMenu } from '@/components/AppearanceMenu';
import { AICopilot } from '@/components/AICopilot';

interface User {
  id: string;
  email: string;
  name: string | null;
  role: string;
  isApproved: boolean;
}

interface LayoutProps {
  children: ReactNode;
}

export function Layout({ children }: LayoutProps) {
  const { user, backendUser, logout } = useAuth();
  const location = useLocation();
  const ability = useAbility();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [adminDropdownOpen, setAdminDropdownOpen] = useState(false);
  const [mobileAdminExpanded, setMobileAdminExpanded] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setAdminDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Check if user is a driver (limited access)
  const isDriverRole = backendUser?.role === 'DRIVER';

  // Define main navigation items (reorganized by workflow priority)
  // coordinatorOnly items are hidden from drivers
  const allNavigation = [
    { name: 'Dashboard', href: '/dashboard', icon: LayoutDashboard, coordinatorOnly: true },
    { name: 'My Schedule', href: '/my-schedule', icon: Calendar, driverOnly: true },
    { name: 'My Profile', href: '/profile', icon: UserCog, driverOnly: true },
    { name: 'War Room', href: '/command-center', icon: Radio, requireRead: 'ScheduleEvent' as const, coordinatorOnly: true },
    { name: 'VIPs', href: '/vips', icon: Users, requireRead: 'VIP' as const, coordinatorOnly: true },
    { name: 'Drivers', href: '/drivers', icon: Car, requireRead: 'Driver' as const, coordinatorOnly: true },
    { name: 'Vehicles', href: '/vehicles', icon: Truck, requireRead: 'Vehicle' as const, coordinatorOnly: true },
    { name: 'Activities', href: '/events', icon: Calendar, requireRead: 'ScheduleEvent' as const, coordinatorOnly: true },
    { name: 'Flights', href: '/flights', icon: Plane, requireRead: 'Flight' as const, coordinatorOnly: true },
  ];

  // Admin dropdown items (nested under Admin)
  const adminItems = [
    { name: 'Users', href: '/users', icon: UserCog },
    { name: 'GPS Tracking', href: '/gps-tracking', icon: Radio },
    { name: 'Admin Tools', href: '/admin-tools', icon: Settings },
  ];

  // Filter navigation based on role and CASL permissions
  const navigation = allNavigation.filter((item) => {
    // Driver-only items
    if (item.driverOnly) return isDriverRole;
    // Coordinator-only items hidden from drivers
    if (item.coordinatorOnly && isDriverRole) return false;
    // Permission-based items
    if (item.requireRead) {
      return ability.can(Action.Read, item.requireRead);
    }
    return true;
  });

  // Show admin dropdown if user can read User resources
  const canAccessAdmin = ability.can(Action.Read, 'User');

  // Fetch pending approvals count for admins
  const { data: users } = useQuery<User[]>({
    queryKey: ['users'],
    queryFn: async () => {
      const { data } = await api.get('/users');
      return data;
    },
    enabled: canAccessAdmin, // Only fetch if user can access admin
  });

  const pendingApprovalsCount = users?.filter((u) => !u.isApproved).length || 0;

  // Fetch driver's own profile if they are a driver
  const isDriver = backendUser?.role === 'DRIVER';
  const { data: myDriverProfile } = useQuery<{ id: string; phone: string | null }>({
    queryKey: ['my-driver-profile'],
    queryFn: async () => {
      const { data } = await api.get('/drivers/me');
      return data;
    },
    enabled: isDriver,
  });

  const driverNeedsPhone = isDriver && myDriverProfile && !myDriverProfile.phone;

  const isActive = (path: string) => location.pathname === path;
  const isAdminActive = adminItems.some(item => isActive(item.href));

  return (
    <div className="min-h-screen bg-muted/30">
      {/* Top Navigation */}
      <nav className="bg-card shadow-soft border-b border-border sticky top-0 z-40 backdrop-blur-sm bg-card/95">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center flex-1 min-w-0">
              {/* Mobile menu button - shows on portrait iPad and smaller */}
              <button
                type="button"
                className="lg:hidden inline-flex items-center justify-center p-2 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary mr-2"
                style={{ minWidth: '44px', minHeight: '44px' }}
                onClick={() => setMobileMenuOpen(true)}
                aria-label="Open menu"
              >
                <Menu className="h-6 w-6" />
              </button>

              <div className="flex-shrink-0 flex items-center">
                <Plane className="h-8 w-8 text-primary" />
                <span className="ml-2 text-xl font-bold text-foreground">
                  VIP Coordinator
                </span>
              </div>

              {/* Desktop navigation - shows on landscape iPad and larger */}
              <div className="hidden lg:ml-6 lg:flex lg:space-x-4 xl:space-x-6 lg:items-center">
                {navigation.map((item) => {
                  const Icon = item.icon;
                  return (
                    <Link
                      key={item.name}
                      to={item.href}
                      className={`inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium transition-colors whitespace-nowrap ${
                        isActive(item.href)
                          ? 'border-primary text-foreground'
                          : 'border-transparent text-muted-foreground hover:border-border hover:text-foreground'
                      }`}
                    >
                      <Icon className="h-4 w-4 mr-1.5" />
                      {item.name}
                    </Link>
                  );
                })}

                {/* Admin Dropdown */}
                {canAccessAdmin && (
                  <div className="relative flex-shrink-0" ref={dropdownRef}>
                    <button
                      onClick={() => setAdminDropdownOpen(!adminDropdownOpen)}
                      className={`inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium transition-colors whitespace-nowrap ${
                        isAdminActive
                          ? 'border-primary text-foreground'
                          : 'border-transparent text-muted-foreground hover:border-border hover:text-foreground'
                      }`}
                    >
                      <Shield className="h-4 w-4 mr-1.5" />
                      Admin
                      {pendingApprovalsCount > 0 && (
                        <span className="ml-1.5 inline-flex items-center justify-center px-2 py-0.5 text-xs font-bold leading-none text-white bg-destructive rounded-full">
                          {pendingApprovalsCount}
                        </span>
                      )}
                      <ChevronDown className={`h-4 w-4 ml-1 transition-transform ${adminDropdownOpen ? 'rotate-180' : ''}`} />
                    </button>

                    {/* Dropdown menu */}
                    {adminDropdownOpen && (
                      <div className="absolute left-0 mt-2 w-48 bg-popover rounded-lg shadow-elevated border border-border z-50 overflow-hidden animate-in fade-in slide-in-from-top-2 duration-150">
                        <div className="py-1">
                          {adminItems.map((item) => {
                            const Icon = item.icon;
                            return (
                              <Link
                                key={item.name}
                                to={item.href}
                                onClick={() => setAdminDropdownOpen(false)}
                                className={`flex items-center px-4 py-2 text-sm transition-colors ${
                                  isActive(item.href)
                                    ? 'bg-primary/10 text-primary'
                                    : 'text-popover-foreground hover:bg-accent'
                                }`}
                              >
                                <Icon className="h-4 w-4 mr-3" />
                                {item.name}
                              </Link>
                            );
                          })}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* User section - modern dropdown */}
            <div className="flex items-center flex-shrink-0 ml-4">
              <UserMenu />
            </div>
          </div>
        </div>
      </nav>

      {/* Mobile menu drawer - overlay */}
      {mobileMenuOpen && (
        <div className="fixed inset-0 z-50 lg:hidden">
          {/* Backdrop */}
          <div
            className="fixed inset-0 bg-black/50 backdrop-blur-sm animate-in fade-in duration-200"
            onClick={() => setMobileMenuOpen(false)}
            aria-hidden="true"
          />

          {/* Drawer panel */}
          <div className="fixed inset-y-0 left-0 w-full max-w-sm bg-card shadow-elevated animate-in slide-in-from-left duration-300">
            <div className="flex flex-col h-full">
              {/* Drawer header */}
              <div className="flex items-center justify-between px-4 h-16 border-b border-border">
                <div className="flex items-center">
                  <Plane className="h-8 w-8 text-primary" />
                  <span className="ml-2 text-xl font-bold text-foreground">
                    VIP Coordinator
                  </span>
                </div>
                <button
                  type="button"
                  className="rounded-md p-2 text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
                  style={{ minWidth: '44px', minHeight: '44px' }}
                  onClick={() => setMobileMenuOpen(false)}
                  aria-label="Close menu"
                >
                  <X className="h-6 w-6" />
                </button>
              </div>

              {/* User info in drawer */}
              <div className="px-4 py-4 border-b border-border bg-muted/50">
                <div className="text-sm font-medium text-foreground">
                  {backendUser?.name || user?.name || user?.email}
                </div>
                {backendUser?.role && (
                  <div className="text-xs text-muted-foreground mt-1">
                    {backendUser.role}
                  </div>
                )}
              </div>

              {/* Appearance settings in drawer */}
              <div className="px-4 py-4 border-b border-border">
                <AppearanceMenu compact />
              </div>

              {/* Navigation links */}
              <nav className="flex-1 px-4 py-4 space-y-1 overflow-y-auto scrollbar-thin">
                {navigation.map((item) => {
                  const Icon = item.icon;
                  return (
                    <Link
                      key={item.name}
                      to={item.href}
                      onClick={() => setMobileMenuOpen(false)}
                      className={`flex items-center px-4 py-3 text-base font-medium rounded-lg transition-colors ${
                        isActive(item.href)
                          ? 'bg-primary/10 text-primary'
                          : 'text-foreground hover:bg-accent'
                      }`}
                      style={{ minHeight: '44px' }}
                    >
                      <Icon className="h-5 w-5 mr-3 flex-shrink-0" />
                      {item.name}
                    </Link>
                  );
                })}

                {/* Admin Section (Expandable) */}
                {canAccessAdmin && (
                  <div className="space-y-1">
                    <button
                      onClick={() => setMobileAdminExpanded(!mobileAdminExpanded)}
                      className={`w-full flex items-center justify-between px-4 py-3 text-base font-medium rounded-lg transition-colors ${
                        isAdminActive
                          ? 'bg-primary/10 text-primary'
                          : 'text-foreground hover:bg-accent'
                      }`}
                      style={{ minHeight: '44px' }}
                    >
                      <div className="flex items-center">
                        <Shield className="h-5 w-5 mr-3 flex-shrink-0" />
                        Admin
                        {pendingApprovalsCount > 0 && (
                          <span className="ml-2 inline-flex items-center justify-center px-2 py-0.5 text-xs font-bold leading-none text-white bg-destructive rounded-full">
                            {pendingApprovalsCount}
                          </span>
                        )}
                      </div>
                      <ChevronDown className={`h-5 w-5 transition-transform ${mobileAdminExpanded ? 'rotate-180' : ''}`} />
                    </button>

                    {/* Nested admin items */}
                    {mobileAdminExpanded && (
                      <div className="ml-4 space-y-1">
                        {adminItems.map((item) => {
                          const Icon = item.icon;
                          return (
                            <Link
                              key={item.name}
                              to={item.href}
                              onClick={() => {
                                setMobileMenuOpen(false);
                                setMobileAdminExpanded(false);
                              }}
                              className={`flex items-center px-4 py-3 text-base rounded-lg transition-colors ${
                                isActive(item.href)
                                  ? 'bg-primary/10 text-primary font-medium'
                                  : 'text-muted-foreground hover:bg-accent hover:text-foreground'
                              }`}
                              style={{ minHeight: '44px' }}
                            >
                              <Icon className="h-4 w-4 mr-3 flex-shrink-0" />
                              {item.name}
                            </Link>
                          );
                        })}
                      </div>
                    )}
                  </div>
                )}
              </nav>

              {/* Logout button at bottom of drawer */}
              <div className="border-t border-border px-4 py-4">
                <button
                  onClick={() => {
                    setMobileMenuOpen(false);
                    logout();
                  }}
                  className="w-full flex items-center justify-center px-4 py-3 border border-transparent text-base font-medium rounded-lg text-primary-foreground bg-primary hover:bg-primary/90 transition-colors shadow-soft"
                  style={{ minHeight: '44px' }}
                >
                  <LogOut className="h-5 w-5 mr-2" />
                  Sign Out
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Driver Phone Number Reminder Banner */}
      {driverNeedsPhone && (
        <div className="bg-amber-50 dark:bg-amber-950/30 border-b border-amber-200 dark:border-amber-800">
          <div className="max-w-7xl mx-auto py-3 px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between gap-4">
              <div className="flex items-center gap-3">
                <div className="flex-shrink-0">
                  <AlertCircle className="h-5 w-5 text-amber-600 dark:text-amber-400" />
                </div>
                <p className="text-sm font-medium text-amber-800 dark:text-amber-200">
                  <Phone className="h-4 w-4 inline mr-1" />
                  Please add your phone number to receive trip notifications via Signal.
                </p>
              </div>
              <Link
                to="/profile"
                className="flex-shrink-0 text-sm font-medium text-amber-700 dark:text-amber-300 hover:text-amber-900 dark:hover:text-amber-100 underline"
              >
                Update Profile →
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* Main Content */}
      <main className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        {children}
      </main>

      {/* AI Copilot - floating chat (only for Admins and Coordinators) */}
      {backendUser && (backendUser.role === 'ADMINISTRATOR' || backendUser.role === 'COORDINATOR') && (
        <AICopilot />
      )}
    </div>
  );
}
