import { ReactNode, useState, useEffect } from 'react'
import { 
  ThemeProvider, 
  ThreeColumnLayout,
  MobileHeader,
  LayoutSidebar,
  FooterLinks,
  ThemeSwitcher,
  Avatar,
  HomeIcon,
  ProfileIcon,
  type Theme,
  type FooterLink
} from '@orchard9ai/design-system'
import { SplashScreen } from '../components/SplashScreen'
import { usePageContext } from 'vike-react/usePageContext'
import '../styles/globals.css'

export { Layout }

function Layout({ children }: { children: ReactNode }) {
  // Start with false to match server rendering (SSR-safe)
  const [showSplash, setShowSplash] = useState(false)
  const [isClient, setIsClient] = useState(false)
  const [showMobileMenu, setShowMobileMenu] = useState(false)
  const [showMobileProfile, setShowMobileProfile] = useState(false)
  const pageContext = usePageContext()
  const currentPath = pageContext.urlPathname

  useEffect(() => {
    // Mark that we're now on the client
    setIsClient(true)
    
    // Check if user has seen splash before
    const hasSeenSplash = sessionStorage.getItem('hasSeenSplash')
    if (!hasSeenSplash) {
      setShowSplash(true)
    }
  }, [])

  const handleSplashComplete = () => {
    setShowSplash(false)
    sessionStorage.setItem('hasSeenSplash', 'true')
  }

  const handleThemeChange = (theme: Theme) => {
    // Optional: Add analytics tracking or custom logic here
    if (typeof window !== 'undefined') {
      // eslint-disable-next-line no-console
      console.log('Theme changed to:', theme)
    }
  }

  // Navigation items
  const navItems = [
    { id: 1, label: 'Home', icon: HomeIcon, href: '/' },
    { id: 2, label: 'About', icon: ProfileIcon, href: '/about' },
    { id: 3, label: 'Layout Demo', icon: ProfileIcon, href: '/layout-demo' },
  ]

  // Footer links
  const footerLinks: FooterLink[] = [
    { label: 'About', href: '/about' },
    { label: 'Terms', href: '/terms' },
    { label: 'Privacy', href: '/privacy' },
    { label: 'Contact', href: '/contact' },
    { label: 'Help', href: '/help' },
  ]

  // Left sidebar content
  const leftSidebarContent = (
    <LayoutSidebar
      header={
        <div className="px-6 py-8">
          <h1 className="text-2xl font-bold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
            {{PROJECT_NAME}}
          </h1>
          <p className="text-sm opacity-60 mt-1">Built with Vite + Vike + Tauri</p>
        </div>
      }
      content={
        <nav className="px-3 pb-4">
          <ul className="menu">
            {navItems.map((item) => {
              const Icon = item.icon;
              const isActive = currentPath === item.href;
              return (
                <li key={item.id}>
                  <a 
                    href={item.href}
                    className={`flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-base-300 transition-colors ${
                      isActive ? 'bg-primary text-primary-content hover:bg-primary' : ''
                    }`}
                  >
                    <Icon className="w-5 h-5 opacity-70" />
                    <span className="font-medium">{item.label}</span>
                  </a>
                </li>
              );
            })}
          </ul>
        </nav>
      }
      footer={
        <FooterLinks 
          links={footerLinks} 
          copyright={`© ${new Date().getFullYear()} {{PROJECT_NAME}}. All rights reserved.`}
        />
      }
    />
  );

  // Right sidebar content
  const rightSidebarContent = (
    <LayoutSidebar
      header={
        <div className="px-6 py-6 border-b border-base-300">
          <h2 className="text-lg font-semibold">Your Profile</h2>
        </div>
      }
      content={
        <div className="px-6 py-6 space-y-8">
          <div className="flex flex-col items-center text-center">
            <Avatar 
              name="Demo User"
              size="xl"
              className="mb-4"
            />
            <h3 className="font-semibold text-lg">Demo User</h3>
            <p className="text-sm opacity-60 mt-1 text-center">@demo</p>
          </div>

          <div className="space-y-4">
            <div className="bg-base-300 rounded-lg p-4">
              <div className="flex justify-between items-baseline mb-2">
                <span className="text-sm font-medium">Sessions</span>
                <span className="text-2xl font-semibold">24</span>
              </div>
              <div className="w-full bg-base-100 rounded-full h-2">
                <div className="bg-primary h-2 rounded-full" style={{ width: '65%' }}></div>
              </div>
            </div>

            <div className="bg-base-300 rounded-lg p-4">
              <div className="flex justify-between items-baseline mb-2">
                <span className="text-sm font-medium">Features Used</span>
                <span className="text-2xl font-semibold">8</span>
              </div>
              <div className="w-full bg-base-100 rounded-full h-2">
                <div className="bg-secondary h-2 rounded-full" style={{ width: '40%' }}></div>
              </div>
            </div>

            {/* Theme Switcher */}
            <div className="bg-base-300 rounded-lg p-4">
              <ThemeSwitcher />
            </div>
          </div>
        </div>
      }
    />
  );

  // Mobile header
  const mobileHeader = (
    <MobileHeader
      onMenuClick={() => setShowMobileMenu(true)}
      onProfileClick={() => setShowMobileProfile(true)}
      title={
        <span className="font-semibold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
          {{PROJECT_NAME}}
        </span>
      }
    />
  );

  // Only show splash if we're on client and conditions are met
  if (isClient && showSplash) {
    return (
      <ThemeProvider initialTheme="grove-dark" onThemeChange={handleThemeChange}>
        <SplashScreen onComplete={handleSplashComplete} />
      </ThemeProvider>
    )
  }

  return (
    <ThemeProvider initialTheme="grove-dark" onThemeChange={handleThemeChange}>
      <ThreeColumnLayout
        leftSidebar={leftSidebarContent}
        rightSidebar={rightSidebarContent}
        mainContent={children}
        mobileHeader={mobileHeader}
        showMobileMenu={showMobileMenu}
        showMobileProfile={showMobileProfile}
      />
    </ThemeProvider>
  )
}