import { useState, useEffect, useCallback, useRef } from 'react'
import { Link, useLocation, useNavigate, Outlet } from 'react-router-dom'
import { useAuthStore } from '@/store/authStore'
import { usePermissions } from '@/hooks/usePermissions'
import { BrandLogo } from '@/components/common/BrandLogo'
import { Menu, X, LogOut, User, Shield, ChevronDown, FolderTree, ListOrdered, Layers } from 'lucide-react'
import { cn } from '@/lib/utils'

interface NavItem {
  path: string
  label: string
  children?: { path: string; label: string; icon: React.ReactNode }[]
}

export function AppLayout() {
  const location = useLocation()
  const navigate = useNavigate()
  const { user, logout } = useAuthStore()
  const { effectiveRole, isSuperAdmin } = usePermissions()
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
  const [flowsDropdownOpen, setFlowsDropdownOpen] = useState(false)
  const flowsDropdownRef = useRef<HTMLDivElement>(null)

  const handleLogout = async () => {
    setMobileMenuOpen(false)
    await logout()
    navigate('/login')
  }

  // Close mobile menu on route change
  const [prevPath, setPrevPath] = useState(location.pathname)
  if (prevPath !== location.pathname) {
    setPrevPath(location.pathname)
    if (mobileMenuOpen) setMobileMenuOpen(false)
    setFlowsDropdownOpen(false)
  }

  // Close on Escape
  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    if (e.key === 'Escape') {
      setMobileMenuOpen(false)
      setFlowsDropdownOpen(false)
    }
  }, [])

  // Close dropdown on outside click
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (flowsDropdownRef.current && !flowsDropdownRef.current.contains(e.target as Node)) {
        setFlowsDropdownOpen(false)
      }
    }
    if (flowsDropdownOpen) {
      document.addEventListener('mousedown', handleClickOutside)
    }
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [flowsDropdownOpen])

  useEffect(() => {
    if (mobileMenuOpen) {
      document.addEventListener('keydown', handleKeyDown)
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = ''
    }
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.body.style.overflow = ''
    }
  }, [mobileMenuOpen, handleKeyDown])

  const isFlowsActive = location.pathname.startsWith('/trees') || location.pathname.startsWith('/flows')

  const navItems: NavItem[] = [
    { path: '/', label: 'Home' },
    {
      path: '/trees',
      label: 'Flows',
      children: [
        { path: '/trees', label: 'All Flows', icon: <Layers className="h-4 w-4 text-white/50" /> },
        { path: '/trees?type=troubleshooting', label: 'Troubleshooting', icon: <FolderTree className="h-4 w-4 text-white/50" /> },
        { path: '/trees?type=procedural', label: 'Procedures', icon: <ListOrdered className="h-4 w-4 text-white/50" /> },
      ],
    },
    { path: '/my-trees', label: 'My Flows' },
    { path: '/sessions', label: 'Sessions' },
    { path: '/shares', label: 'My Shares' },
    { path: '/account', label: 'Account' },
    ...(isSuperAdmin ? [{ path: '/admin', label: 'Admin Panel' }] : []),
  ]

  return (
    <div className="min-h-screen bg-black">
      {/* Subtle radial overlay for depth */}
      <div className="pointer-events-none fixed inset-0 bg-[radial-gradient(circle_at_50%_0%,rgba(100,100,120,0.03),transparent_50%),radial-gradient(circle_at_80%_80%,rgba(80,80,100,0.02),transparent_50%)]" />

      {/* Header */}
      <header className="sticky top-0 z-50 border-b border-white/[0.06] bg-black/80 backdrop-blur-xl">
        <div className="container mx-auto flex h-16 items-center justify-between px-4">
          <div className="flex items-center gap-8">
            {/* Mobile hamburger */}
            <button
              onClick={() => setMobileMenuOpen(true)}
              className="rounded-xl p-2 text-white/50 hover:bg-white/10 hover:text-white transition-all sm:hidden"
              aria-label="Open menu"
            >
              <Menu className="h-5 w-5" />
            </button>

            {/* Logo */}
            <Link to="/" className="flex items-center gap-3 group">
              <div className="w-9 h-9 rounded-xl bg-white flex items-center justify-center transition-transform group-hover:scale-105">
                <BrandLogo size="sm" className="h-5 w-5 invert" />
              </div>
              <span className="text-xl font-semibold text-white tracking-tight">
                ResolutionFlow
              </span>
            </Link>

            {/* Desktop Navigation */}
            <nav className="hidden items-center gap-1 sm:flex">
              {navItems.map((item) => {
                if (item.children) {
                  return (
                    <div key={item.path} className="relative" ref={flowsDropdownRef}>
                      <button
                        onClick={() => setFlowsDropdownOpen(!flowsDropdownOpen)}
                        className={cn(
                          'flex items-center gap-1 rounded-xl px-4 py-2 text-sm font-medium transition-all',
                          isFlowsActive
                            ? 'bg-white/10 text-white border border-white/20'
                            : 'text-white/50 hover:text-white hover:bg-white/[0.06]'
                        )}
                      >
                        {item.label}
                        <ChevronDown className={cn('h-3.5 w-3.5 transition-transform', flowsDropdownOpen && 'rotate-180')} />
                      </button>
                      {flowsDropdownOpen && (
                        <div className="absolute left-0 z-50 mt-1 w-52 rounded-lg border border-white/10 bg-black/95 p-1 shadow-xl backdrop-blur-sm">
                          {item.children.map((child) => (
                            <Link
                              key={child.path}
                              to={child.path}
                              onClick={() => setFlowsDropdownOpen(false)}
                              className="flex items-center gap-3 rounded-md px-3 py-2.5 text-sm text-white/70 hover:bg-white/10 hover:text-white"
                            >
                              {child.icon}
                              {child.label}
                            </Link>
                          ))}
                        </div>
                      )}
                    </div>
                  )
                }

                const isActive = item.path === '/'
                  ? location.pathname === '/'
                  : location.pathname.startsWith(item.path)

                return (
                  <Link
                    key={item.path}
                    to={item.path}
                    className={cn(
                      'rounded-xl px-4 py-2 text-sm font-medium transition-all',
                      isActive
                        ? 'bg-white/10 text-white border border-white/20'
                        : 'text-white/50 hover:text-white hover:bg-white/[0.06]'
                    )}
                  >
                    {item.label}
                  </Link>
                )
              })}
            </nav>
          </div>

          {/* Right side controls */}
          <div className="flex items-center gap-3">
            {/* User info */}
            <div className="hidden items-center gap-3 sm:flex">
              <div className="flex items-center gap-2 rounded-xl bg-white/[0.06] px-3 py-1.5 border border-white/10">
                <User className="h-4 w-4 text-white/40" />
                <span className="text-sm text-white/70">
                  {user?.name || user?.email}
                </span>
              </div>

              {/* Role badge */}
              {effectiveRole && effectiveRole !== 'engineer' && (
                <div className="px-3 py-1.5 rounded-xl bg-white/10 border border-white/20">
                  <span className="flex items-center gap-1.5 text-xs text-white font-semibold">
                    <Shield className="h-3 w-3" />
                    {effectiveRole === 'super_admin' ? 'Super Admin' :
                     effectiveRole === 'owner' ? 'Owner' :
                     'Viewer'}
                  </span>
                </div>
              )}
            </div>

            {/* Logout button */}
            <button
              onClick={handleLogout}
              className={cn(
                'hidden items-center gap-2 rounded-xl px-4 py-2 text-sm font-medium sm:flex',
                'text-white/50 hover:text-white hover:bg-white/10 transition-all',
                'border border-white/10 hover:border-white/20'
              )}
            >
              <LogOut className="h-4 w-4" />
              Logout
            </button>
          </div>
        </div>
      </header>

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

          {/* Drawer */}
          <nav className="absolute inset-y-0 left-0 w-72 border-r border-white/[0.06] bg-black shadow-2xl animate-in slide-in-from-left duration-300">
            <div className="flex h-16 items-center justify-between border-b border-white/[0.06] px-4">
              <Link to="/" className="flex items-center gap-3">
                <div className="w-9 h-9 rounded-xl bg-white flex items-center justify-center">
                  <BrandLogo size="sm" className="h-5 w-5 invert" />
                </div>
                <span className="text-xl font-semibold text-white tracking-tight">
                  ResolutionFlow
                </span>
              </Link>
              <button
                onClick={() => setMobileMenuOpen(false)}
                className="rounded-xl p-2 text-white/50 hover:bg-white/10 hover:text-white transition-all"
                aria-label="Close menu"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <div className="flex flex-col p-4">
              {/* User info */}
              <div className="mb-4 border-b border-white/[0.06] pb-4">
                <div className="flex items-center gap-2 mb-2">
                  <User className="h-4 w-4 text-white/40" />
                  <p className="text-sm font-medium text-white">
                    {user?.name || user?.email}
                  </p>
                </div>
                {effectiveRole && effectiveRole !== 'engineer' && (
                  <div className="inline-flex px-3 py-1.5 rounded-xl bg-white/10 border border-white/20">
                    <span className="flex items-center gap-1.5 text-xs text-white font-semibold">
                      <Shield className="h-3 w-3" />
                      {effectiveRole === 'super_admin' ? 'Super Admin' :
                       effectiveRole === 'owner' ? 'Owner' :
                       'Viewer'}
                    </span>
                  </div>
                )}
              </div>

              {/* Nav items */}
              <div className="space-y-1">
                {navItems.map((item) => {
                  if (item.children) {
                    return (
                      <div key={item.path}>
                        <div className={cn(
                          'px-4 py-2 text-xs font-semibold uppercase tracking-wider',
                          isFlowsActive ? 'text-white/60' : 'text-white/30'
                        )}>
                          {item.label}
                        </div>
                        <div className="space-y-0.5">
                          {item.children.map((child) => (
                            <Link
                              key={child.path}
                              to={child.path}
                              className={cn(
                                'flex items-center gap-3 rounded-xl px-4 py-3 text-sm font-medium transition-all ml-1',
                                'text-white/50 hover:text-white hover:bg-white/[0.06]'
                              )}
                            >
                              {child.icon}
                              {child.label}
                            </Link>
                          ))}
                        </div>
                      </div>
                    )
                  }

                  const isActive = item.path === '/'
                    ? location.pathname === '/'
                    : location.pathname.startsWith(item.path)

                  return (
                    <Link
                      key={item.path}
                      to={item.path}
                      className={cn(
                        'block rounded-xl px-4 py-3 text-sm font-medium transition-all',
                        isActive
                          ? 'bg-white/10 text-white border border-white/20'
                          : 'text-white/50 hover:text-white hover:bg-white/[0.06]'
                      )}
                    >
                      {item.label}
                    </Link>
                  )
                })}
              </div>

              {/* Logout */}
              <div className="mt-4 border-t border-white/[0.06] pt-4">
                <button
                  onClick={handleLogout}
                  className={cn(
                    'w-full flex items-center gap-2 rounded-xl px-4 py-3 text-sm font-medium',
                    'text-white/50 hover:text-white hover:bg-white/10 transition-all',
                    'border border-white/10 hover:border-white/20'
                  )}
                >
                  <LogOut className="h-4 w-4" />
                  Logout
                </button>
              </div>
            </div>
          </nav>
        </div>
      )}

      {/* Main Content */}
      <main className="relative animate-in fade-in duration-500">
        <Outlet />
      </main>
    </div>
  )
}

export default AppLayout
