import { useState, useCallback, useEffect, useRef } from 'react'
import { Sidebar } from './Sidebar'
import { Header } from './Header'
import { useDirection } from '@/hooks/useDirection'
import { useIndexingHeartbeat } from '@/hooks/useIndexingHeartbeat'
import { WizardFloatingPanel } from '@/components/wizard/WizardFloatingPanel'
import { CreditAlertBanner } from './CreditAlertBanner'
import { useNavigationGuard } from '@/contexts/NavigationGuardContext'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'

interface AdminLayoutProps {
  children: React.ReactNode
}

export function AdminLayout({ children }: AdminLayoutProps) {
  const { direction } = useDirection()
  const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false)
  const {
    isBlocked,
    checkGuard,
    isNavigatingRef,
    isModalOpen,
    saveError,
    cancelNavigation,
    saveAndProceed,
    discardAndProceed,
    saveAlwaysAndProceed,
  } = useNavigationGuard()

  // Global indexing heartbeat: ensures background indexing continues even when
  // the admin is not on the Knowledge Base page. See useIndexingHeartbeat docs.
  useIndexingHeartbeat()

  const toggleMobileSidebar = useCallback(() => setIsMobileSidebarOpen(prev => !prev), [])
  const closeMobileSidebar = useCallback(() => setIsMobileSidebarOpen(false), [])

  // Guard browser back/forward via hashchange
  const currentHashRef = useRef(window.location.hash)
  useEffect(() => {
    const handleHashChange = () => {
      // Skip if this hash change was triggered by an intentional (confirmed) navigation
      if (isNavigatingRef.current) {
        currentHashRef.current = window.location.hash
        return
      }
      if (!isBlocked()) {
        currentHashRef.current = window.location.hash
        return
      }
      const targetHash = window.location.hash
      const previousHash = currentHashRef.current
      // Revert the hash to prevent premature navigation
      window.history.replaceState(null, '', previousHash)

      checkGuard(() => {
        currentHashRef.current = targetHash
        window.location.hash = targetHash.replace(/^#/, '')
      })
    }

    window.addEventListener('hashchange', handleHashChange)
    return () => window.removeEventListener('hashchange', handleHashChange)
  }, [isBlocked, checkGuard, isNavigatingRef])
  
  return (
    <div 
      className="boostbot-admin flex min-h-screen bg-gray-50" 
      dir={direction}
    >
      {/* Sidebar - Fixed on desktop, overlay on mobile */}
      <Sidebar
        isMobileOpen={isMobileSidebarOpen}
        onMobileClose={closeMobileSidebar}
      />
      
      {/* Main Content - Takes remaining space, prevents overflow */}
      <div className="flex-1 flex flex-col min-h-screen min-w-0">
        {/* Header */}
        <Header onMobileMenuToggle={toggleMobileSidebar} />
        
        {/* Low credit warning banner */}
        <CreditAlertBanner />
        
        {/* Page Content */}
        <main className="flex-1 p-6 overflow-auto min-w-0">
          {children}
        </main>
      </div>

      {/* Floating Wizard Indicator — visible during onboarding */}
      <WizardFloatingPanel />

      {/* Global unsaved-changes modal (survives page unmount) */}
      <UnsavedChangesModal
        isOpen={isModalOpen}
        onCancel={cancelNavigation}
        onDiscard={discardAndProceed}
        onSave={saveAndProceed}
        onSaveAlways={saveAlwaysAndProceed}
        errorMessage={saveError}
      />
    </div>
  )
}




