import React, { useState } from 'react';
import { Outlet, Link, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useSocket } from '../contexts/SocketContext';
import DebugToggle from './DebugToggle';
import {
  HomeIcon,
  MapIcon,
  ServerIcon,
  ExclamationTriangleIcon,
  BellIcon,
  UserIcon,
  Bars3Icon,
  XMarkIcon,
  SignalIcon,
  WifiIcon,
  BugAntIcon
} from '@heroicons/react/24/outline';
import classNames from 'classnames';

const baseNavigation = [
  { name: 'Dashboard', href: '/', icon: HomeIcon },
  { name: 'Map View', href: '/map', icon: MapIcon },
  { name: 'Devices', href: '/devices', icon: ServerIcon },
  { name: 'Detections', href: '/detections', icon: ExclamationTriangleIcon },
  { name: 'Alerts', href: '/alerts', icon: BellIcon },
];

const adminNavigation = [
  { name: 'Debug', href: '/debug', icon: BugAntIcon },
];

const Layout = () => {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const { user, logout } = useAuth();
  const { connected, recentDetections } = useSocket();
  const location = useLocation();

  // Build navigation based on user role - ensure it's always an array
  const navigation = React.useMemo(() => {
    if (!user) {
      return baseNavigation; // Return base navigation if user not loaded yet
    }
    return user.role === 'admin' 
      ? [...baseNavigation, ...adminNavigation]
      : baseNavigation;
  }, [user?.role]);

  return (
    <div className="min-h-screen flex bg-gray-100">
      {/* Mobile sidebar */}
      <div className={classNames(
        'fixed inset-0 flex z-40 md:hidden',
        sidebarOpen ? 'block' : 'hidden'
      )}>
        <div className="fixed inset-0 bg-gray-600 bg-opacity-75" onClick={() => setSidebarOpen(false)} />
        <div className="relative flex-1 flex flex-col max-w-xs w-full pt-5 pb-4 bg-white">
          <div className="absolute top-0 right-0 -mr-12 pt-2">
            <button
              type="button"
              className="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"
              onClick={() => setSidebarOpen(false)}
            >
              <XMarkIcon className="h-6 w-6 text-white" />
            </button>
          </div>
          <SidebarContent navigation={navigation} />
        </div>
      </div>

      {/* Static sidebar for desktop */}
      <div className="hidden md:flex md:flex-shrink-0">
        <div className="flex flex-col w-64">
          <div className="flex flex-col flex-grow pt-5 pb-4 overflow-y-auto bg-white border-r border-gray-200">
            <SidebarContent navigation={navigation} />
          </div>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 flex flex-col min-h-screen">
        <div className="relative z-10 flex-shrink-0 flex h-16 bg-white border-b border-gray-200">
          <button
            type="button"
            className="px-4 border-r border-gray-200 text-gray-400 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary-500 md:hidden"
            onClick={() => setSidebarOpen(true)}
          >
            <Bars3Icon className="h-6 w-6" />
          </button>
          
          {/* Top navigation */}
          <div className="flex-1 px-4 flex justify-between items-center">
            <div className="flex-1 flex">
              <h1 className="text-xl font-semibold text-gray-900">
                {navigation?.find(item => item.href === location.pathname)?.name || 'Drone Detection System'}
              </h1>
            </div>
            
            <div className="ml-4 flex items-center md:ml-6 space-x-4">
              {/* Connection status */}
              <div className="flex items-center space-x-2">
                <div className={classNames(
                  'flex items-center space-x-1 px-2 py-1 rounded-full text-xs font-medium',
                  connected 
                    ? 'bg-success-100 text-success-800' 
                    : 'bg-danger-100 text-danger-800'
                )}>
                  {connected ? (
                    <WifiIcon className="h-3 w-3" />
                  ) : (
                    <SignalIcon className="h-3 w-3" />
                  )}
                  <span>{connected ? 'Connected' : 'Disconnected'}</span>
                </div>
              </div>

              {/* Recent detections count */}
              {recentDetections.length > 0 && (
                <div className="flex items-center space-x-1 px-2 py-1 bg-danger-100 text-danger-800 rounded-full text-xs font-medium">
                  <ExclamationTriangleIcon className="h-3 w-3" />
                  <span>{recentDetections.length} recent</span>
                </div>
              )}

              {/* User menu */}
              <div className="ml-3 relative">
                <div className="flex items-center space-x-2">
                  <div className="flex items-center space-x-1 text-sm text-gray-700">
                    <UserIcon className="h-4 w-4" />
                    <span>{user?.username}</span>
                  </div>
                  <button
                    onClick={logout}
                    className="text-sm text-gray-500 hover:text-gray-700"
                  >
                    Logout
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Page content */}
        <main className="flex-1">
          <div className="py-6">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
              <Outlet />
            </div>
          </div>
        </main>
        
        {/* Debug Toggle (floating button) */}
        <DebugToggle />
      </div>
    </div>
  );
};

const SidebarContent = ({ navigation }) => {
  const location = useLocation();

  return (
    <>
      <div className="flex items-center flex-shrink-0 px-4">
        <div className="flex items-center space-x-2">
          <div className="w-8 h-8 bg-primary-600 rounded-lg flex items-center justify-center">
            <ExclamationTriangleIcon className="h-5 w-5 text-white" />
          </div>
          <h1 className="text-lg font-bold text-gray-900">
            Drone Detector
          </h1>
        </div>
      </div>
      
      <div className="mt-5 flex-grow flex flex-col">
        <nav className="flex-1 px-2 space-y-1">
          {Array.isArray(navigation) && navigation.map((item) => {
            const isActive = location.pathname === item.href;
            return (
              <Link
                key={item.name}
                to={item.href}
                className={classNames(
                  isActive
                    ? 'bg-primary-100 border-primary-500 text-primary-700'
                    : 'border-transparent text-gray-600 hover:bg-gray-50 hover:text-gray-900',
                  'group flex items-center px-2 py-2 text-sm font-medium border-l-4 transition-colors duration-200'
                )}
              >
                <item.icon
                  className={classNames(
                    isActive
                      ? 'text-primary-500'
                      : 'text-gray-400 group-hover:text-gray-500',
                    'mr-3 h-5 w-5'
                  )}
                />
                {item.name}
              </Link>
            );
          })}
        </nav>
      </div>
    </>
  );
};

export default Layout;
