import { useState, useEffect } from 'react'
import { Sidebar } from './Sidebar'
import { TopNavbar } from './TopNavbar'
import { DashboardHome } from './DashboardHome'
import { UserManagement } from './UserManagement'
import { ExperimentManagement } from './ExperimentManagement'
import { DataEntry } from './DataEntry'
// VisionSystem is now loaded as a microfrontend - see RemoteVisionSystem below
// import { VisionSystem } from './VisionSystem'
// Scheduling is now loaded as a microfrontend - see RemoteScheduling below
// import { Scheduling } from './Scheduling'
import React, { Suspense } from 'react'
import { loadRemoteComponent } from '../lib/loadRemote'
import { ErrorBoundary } from './ErrorBoundary'
import { isFeatureEnabled } from '../lib/featureFlags'
import { UserProfile } from './UserProfile'
import { userManagement, type User } from '../lib/supabase'

interface DashboardLayoutProps {
  onLogout: () => void
  currentRoute: string
}

export function DashboardLayout({ onLogout, currentRoute }: DashboardLayoutProps) {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentView, setCurrentView] = useState('dashboard')
  const [isExpanded, setIsExpanded] = useState(false)
  const [isMobileOpen, setIsMobileOpen] = useState(false)

  // Valid dashboard views
  const validViews = ['dashboard', 'user-management', 'experiments', 'analytics', 'data-entry', 'vision-system', 'scheduling', 'video-library', 'profile']

  // Save current view to localStorage
  const saveCurrentView = (view: string) => {
    try {
      localStorage.setItem('dashboard-current-view', view)
    } catch (error) {
      console.warn('Failed to save current view to localStorage:', error)
    }
  }

  // Get saved view from localStorage
  const getSavedView = (): string => {
    try {
      const savedView = localStorage.getItem('dashboard-current-view')
      return savedView && validViews.includes(savedView) ? savedView : 'dashboard'
    } catch (error) {
      console.warn('Failed to get saved view from localStorage:', error)
      return 'dashboard'
    }
  }

  // Save sidebar expanded state to localStorage
  const saveSidebarState = (expanded: boolean) => {
    try {
      localStorage.setItem('sidebar-expanded', String(expanded))
    } catch (error) {
      console.warn('Failed to save sidebar state to localStorage:', error)
    }
  }

  // Get saved sidebar state from localStorage
  const getSavedSidebarState = (): boolean => {
    try {
      const saved = localStorage.getItem('sidebar-expanded')
      return saved === 'true'
    } catch (error) {
      console.warn('Failed to get saved sidebar state from localStorage:', error)
      return false
    }
  }

  // Check if user has access to a specific view
  const hasAccessToView = (view: string): boolean => {
    if (!user) return false

    // Admin-only views
    if (view === 'user-management') {
      return user.roles.includes('admin')
    }

    // All other views are accessible to authenticated users
    return true
  }

  // Handle view change with persistence and URL updates
  const handleViewChange = (view: string) => {
    if (validViews.includes(view) && hasAccessToView(view)) {
      setCurrentView(view)
      saveCurrentView(view)

      // Update URL
      const newPath = view === 'dashboard' ? '/' : `/${view}`
      window.history.pushState({}, '', newPath)
    }
  }

  useEffect(() => {
    fetchUserProfile()
    // Load saved sidebar state
    const savedSidebarState = getSavedSidebarState()
    setIsExpanded(savedSidebarState)
  }, [])

  // Restore saved view when user is loaded
  useEffect(() => {
    if (user) {
      const savedView = getSavedView()
      if (hasAccessToView(savedView)) {
        setCurrentView(savedView)
      } else {
        // If user doesn't have access to saved view, default to dashboard
        setCurrentView('dashboard')
        saveCurrentView('dashboard')
      }
    }
  }, [user])

  // Handle route changes for scheduling sub-routes
  useEffect(() => {
    if (currentRoute.startsWith('/scheduling')) {
      setCurrentView('scheduling')
    } else if (currentRoute === '/') {
      // Handle root route - use saved view or default to dashboard
      if (user) {
        const savedView = getSavedView()
        if (hasAccessToView(savedView)) {
          setCurrentView(savedView)
        } else {
          setCurrentView('dashboard')
        }
      }
    } else {
      // Handle other routes by extracting the view name
      const routeView = currentRoute.substring(1) // Remove leading slash
      if (validViews.includes(routeView) && hasAccessToView(routeView)) {
        setCurrentView(routeView)
      }
    }
  }, [currentRoute, user])

  const fetchUserProfile = async () => {
    try {
      setLoading(true)
      setError(null)

      const currentUser = await userManagement.getCurrentUser()
      if (currentUser) {
        setUser(currentUser)
      } else {
        setError('No authenticated user found')
      }
    } catch (err) {
      setError('Failed to fetch user profile')
      console.error('Profile fetch error:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleLogout = async () => {
    // Call the logout function passed from parent
    onLogout()
  }

  const toggleSidebar = () => {
    const newState = !isExpanded
    setIsExpanded(newState)
    saveSidebarState(newState)
  }

  const toggleMobileSidebar = () => {
    setIsMobileOpen(!isMobileOpen)
  }

  const handleToggleSidebar = () => {
    if (window.innerWidth >= 1024) {
      toggleSidebar()
    } else {
      toggleMobileSidebar()
    }
  }

  const LocalVideoPlaceholder = () => (<div className="p-6">Video module not enabled.</div>)
  const RemoteVideoLibrary = loadRemoteComponent(
    isFeatureEnabled('enableVideoModule'),
    () => import('videoRemote/App'),
    LocalVideoPlaceholder as any
  ) as unknown as React.ComponentType

  const LocalVisionSystemPlaceholder = () => (<div className="p-6">Vision System module not enabled.</div>)
  const RemoteVisionSystem = loadRemoteComponent(
    isFeatureEnabled('enableVisionSystemModule'),
    () => import('visionSystemRemote/App'),
    LocalVisionSystemPlaceholder as any
  ) as unknown as React.ComponentType

  const LocalSchedulingPlaceholder = () => (<div className="p-6">Scheduling module not enabled.</div>)
  const RemoteScheduling = loadRemoteComponent(
    isFeatureEnabled('enableSchedulingModule'),
    () => import('schedulingRemote/App'),
    LocalSchedulingPlaceholder as any
  ) as unknown as React.ComponentType<{ user: User; currentRoute: string }>

  const renderCurrentView = () => {
    if (!user) return null

    switch (currentView) {
      case 'dashboard':
        return <DashboardHome user={user} />
      case 'user-management':
        if (user.roles.includes('admin')) {
          return <UserManagement />
        } else {
          return (
            <div className="p-6">
              <div className="bg-red-50 border border-red-200 rounded-md p-4">
                <div className="text-sm text-red-700">
                  Access denied. You need admin privileges to access user management.
                </div>
              </div>
            </div>
          )
        }
      case 'experiments':
        return <ExperimentManagement />
      case 'analytics':
        return (
          <div className="p-6">
            <h1 className="text-2xl font-bold text-gray-900 mb-4">Analytics</h1>
            <div className="bg-green-50 border border-green-200 rounded-md p-4">
              <div className="text-sm text-green-700">
                Analytics module coming soon...
              </div>
            </div>
          </div>
        )
      case 'data-entry':
        return <DataEntry />
      case 'vision-system':
        return (
          <ErrorBoundary>
            <Suspense fallback={<div className="p-6">Loading vision system module...</div>}>
              <RemoteVisionSystem />
            </Suspense>
          </ErrorBoundary>
        )
      case 'scheduling':
        return (
          <ErrorBoundary autoRetry={true} retryDelay={2000} maxRetries={3}>
            <Suspense fallback={<div className="p-6">Loading scheduling module...</div>}>
              <RemoteScheduling user={user} currentRoute={currentRoute} />
            </Suspense>
          </ErrorBoundary>
        )
      case 'video-library':
        return (
          <ErrorBoundary>
            <Suspense fallback={<div className="p-6">Loading video module...</div>}>
              <RemoteVideoLibrary />
            </Suspense>
          </ErrorBoundary>
        )
      case 'profile':
        return <UserProfile user={user} />
      default:
        return <DashboardHome user={user} />
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-brand-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading dashboard...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="max-w-md w-full">
          <div className="rounded-2xl bg-error-50 border border-error-200 p-4 dark:bg-error-500/15 dark:border-error-500/20">
            <div className="text-sm text-error-700 dark:text-error-500">{error}</div>
          </div>
          <button
            onClick={handleLogout}
            className="mt-4 w-full flex justify-center py-2.5 px-4 border border-transparent text-sm font-medium rounded-lg text-white bg-gray-600 hover:bg-gray-700 dark:bg-gray-700 dark:hover:bg-gray-600 transition-colors"
          >
            Back to Login
          </button>
        </div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="text-gray-600 dark:text-gray-400">No user data available</div>
          <button
            onClick={handleLogout}
            className="mt-4 px-4 py-2.5 bg-gray-600 text-white rounded-lg hover:bg-gray-700 dark:bg-gray-700 dark:hover:bg-gray-600 transition-colors"
          >
            Back to Login
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen xl:flex">
      <div>
        <Sidebar
          user={user}
          currentView={currentView}
          onViewChange={handleViewChange}
          isExpanded={isExpanded}
          isMobileOpen={isMobileOpen}
        />
        {/* Backdrop for mobile */}
        {isMobileOpen && (
          <div
            className="fixed inset-0 z-40 bg-gray-900/50 lg:hidden"
            onClick={() => setIsMobileOpen(false)}
          />
        )}
      </div>
      <div
        className={`flex-1 transition-all duration-300 ease-in-out bg-gray-50 dark:bg-gray-900 flex flex-col min-h-0 ${isExpanded ? "lg:ml-[290px]" : "lg:ml-[90px]"
          } ${isMobileOpen ? "ml-0" : ""}`}
      >
        <TopNavbar
          user={user}
          onLogout={handleLogout}
          currentView={currentView}
          onToggleSidebar={handleToggleSidebar}
          isSidebarOpen={isMobileOpen}
          onNavigateToProfile={() => handleViewChange('profile')}
        />
        <div className="flex-1 min-h-0 overflow-hidden p-4 md:p-6">
          {renderCurrentView()}
        </div>
      </div>
    </div>
  )
}
