import { useCallback, useState } from 'react'
import { Outlet, Link, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { useInactivityTimeout } from '../hooks/useInactivityTimeout'

const INACTIVITY_TIMEOUT_MS = 30 * 60 * 1000

type NavItem = {
  path: string
  label: string
  icon: string
  featureKey?: string
}

export default function Layout() {
  const location = useLocation()
  const { username, logout, isAuthenticated, hasPermission } = useAuth()
  const [maintenanceExpanded, setMaintenanceExpanded] = useState(true)

  const handleInactivityLogout = useCallback(() => {
    logout()
  }, [logout])

  useInactivityTimeout({
    timeoutMs: INACTIVITY_TIMEOUT_MS,
    onTimeout: handleInactivityLogout,
    isEnabled: isAuthenticated,
  })

  const primaryNavItems: NavItem[] = [
    { path: '/scan', label: 'Scan', icon: '🗂️', featureKey: 'scan' },
    { path: '/process', label: 'Process', icon: '⚙️', featureKey: 'process' },
    { path: '/search', label: 'Search Photos', icon: '🔍', featureKey: 'search_photos' },
    { path: '/identify', label: 'Identify People', icon: '👤', featureKey: 'identify_people' },
    { path: '/auto-match', label: 'Auto-Match', icon: '🤖', featureKey: 'auto_match' },
    { path: '/modify', label: 'Modify People', icon: '✏️', featureKey: 'modify_people' },
    { path: '/tags', label: 'Tag Photos', icon: '🏷️', featureKey: 'tag_photos' },
  ]

  const maintenanceNavItems: NavItem[] = [
    { path: '/faces-maintenance', label: 'Faces', icon: '🔧', featureKey: 'faces_maintenance' },
    { path: '/approve-identified', label: 'User Identified Faces', icon: '✅', featureKey: 'user_identified' },
    { path: '/reported-photos', label: 'User Reported Photos', icon: '🚩', featureKey: 'user_reported' },
    { path: '/pending-linkages', label: 'User Tagged Photos', icon: '🔖', featureKey: 'user_tagged' },
    { path: '/pending-photos', label: 'User Uploaded Photos', icon: '📤', featureKey: 'user_uploaded' },
    { path: '/manage-users', label: 'Users', icon: '👥', featureKey: 'manage_users' },
  ]

  const footerNavItems: NavItem[] = [{ path: '/help', label: 'Help', icon: '📚' }]

  const filterNavItems = (items: NavItem[]) =>
    items.filter((item) => !item.featureKey || hasPermission(item.featureKey))

  const renderNavLink = (
    item: { path: string; label: string; icon: string },
    extraClasses = ''
  ) => {
    const isActive = location.pathname === item.path
    return (
      <Link
        key={item.path}
        to={item.path}
        className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
          isActive ? 'bg-blue-50 text-blue-700' : 'text-gray-700 hover:bg-gray-50'
        } ${extraClasses}`}
      >
        <span>{item.icon}</span>
        <span>{item.label}</span>
      </Link>
    )
  }

  const visiblePrimary = filterNavItems(primaryNavItems)
  const visibleMaintenance = filterNavItems(maintenanceNavItems)
  const visibleFooter = filterNavItems(footerNavItems)

  // Get page title based on route
  const getPageTitle = () => {
    const route = location.pathname
    if (route === '/') return '🏠 Home Page'
    if (route === '/scan') return '🗂️ Scan Photos'
    if (route === '/process') return '⚙️ Process Faces'
    if (route === '/search') return '🔍 Search Photos'
    if (route === '/identify') return '👤 Identify'
    if (route === '/auto-match') return '🤖 Auto-Match Faces'
    if (route === '/modify') return '✏️ Modify Identified'
    if (route === '/tags') return '🏷️ Photos tagging interface'
    if (route === '/manage-photos') return 'Manage Photos'
    if (route === '/faces-maintenance') return '🔧 Faces Maintenance'
    if (route === '/approve-identified') return '✅ Approve Identified'
    if (route === '/manage-users') return '👥 Manage Users'
    if (route === '/reported-photos') return '🚩 Reported Photos'
    if (route === '/pending-linkages') return '🔖 User Tagged Photos'
    if (route === '/pending-photos') return '📤 Manage User Uploaded Photos'
    if (route === '/settings') return 'Settings'
    if (route === '/help') return '📚 Help'
    return 'PunimTag'
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Top bar */}
      <div className="bg-white border-b border-gray-200 shadow-sm">
        <div className="flex">
          {/* Left sidebar - fixed position with logo */}
          <div className="fixed left-0 top-0 w-64 bg-white border-r border-gray-200 h-20 flex items-center justify-center px-4 z-10">
            <Link to="/" className="flex items-center justify-center hover:opacity-80 transition-opacity">
              <img 
                src="/logo.png" 
                alt="PunimTag" 
                className="h-12 w-auto"
                onError={(e) => {
                  // Fallback if logo.png doesn't exist, try logo.svg
                  const target = e.target as HTMLImageElement
                  if (target.src.endsWith('logo.png')) {
                    target.src = '/logo.svg'
                  }
                }}
              />
            </Link>
          </div>
          {/* Header content - aligned with main content */}
          <div className="ml-64 flex-1 px-4">
            <div className="flex justify-between items-center h-20">
              <div className="flex items-center">
                <h1 className="text-lg font-bold text-gray-900">{getPageTitle()}</h1>
              </div>
              <div className="flex items-center gap-4">
                <span className="text-sm text-gray-600">{username}</span>
                <button
                  onClick={logout}
                  className="px-3 py-1 text-sm text-gray-600 hover:text-gray-900"
                >
                  Logout
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="flex relative">
        {/* Left sidebar - fixed position */}
        <div className="fixed left-0 top-20 w-64 bg-white border-r border-gray-200 h-[calc(100vh-5rem)] overflow-y-auto">
          <nav className="p-4 space-y-1">
            {visiblePrimary.map((item) => renderNavLink(item))}

            {visibleMaintenance.length > 0 && (
              <div className="mt-4">
                <button
                  type="button"
                  onClick={() => setMaintenanceExpanded((prev) => !prev)}
                  className="w-full px-3 py-2 text-xs font-semibold uppercase tracking-wide text-gray-500 flex items-center justify-between hover:text-gray-700"
                >
                  <span>Maintenance</span>
                  <span>{maintenanceExpanded ? '▼' : '▶'}</span>
                </button>
                {maintenanceExpanded && (
                  <div className="mt-1 space-y-1">
                    {visibleMaintenance.map((item) => renderNavLink(item, 'ml-4'))}
                  </div>
                )}
              </div>
            )}

            {visibleFooter.length > 0 && (
              <div className="mt-4 space-y-1">
                {visibleFooter.map((item) => renderNavLink(item))}
              </div>
            )}
          </nav>
        </div>

        {/* Main content - with left margin to account for fixed sidebar */}
        <div className="flex-1 ml-64 p-4">
          <Outlet />
        </div>
      </div>
    </div>
  )
}

