'use client'

import { useState, useEffect } from 'react'
import { useTheme } from '@/contexts/ThemeContext'
import { Button } from '@/components/ui/button'
import { Sun, Moon, Monitor, ChevronDown } from 'lucide-react'
import { cn } from '@/lib/utils'

interface ThemeToggleProps {
  className?: string
  showLabel?: boolean
  variant?: 'button' | 'dropdown'
}

const themeOptions = [
  {
    value: 'light' as const,
    label: { en: 'Light', zh: '浅色' },
    icon: Sun,
  },
  {
    value: 'dark' as const,
    label: { en: 'Dark', zh: '深色' },
    icon: Moon,
  },
  {
    value: 'system' as const,
    label: { en: 'System', zh: '跟随系统' },
    icon: Monitor,
  },
]

export function ThemeToggle({ 
  className, 
  showLabel = false, 
  variant = 'button' 
}: ThemeToggleProps) {
  const { theme, setTheme } = useTheme()
  const [mounted, setMounted] = useState(false)
  const [isOpen, setIsOpen] = useState(false)
  const [currentLanguage, setCurrentLanguage] = useState<'en' | 'zh'>('en')

  // Prevent hydration mismatch
  useEffect(() => {
    setMounted(true)
    
    // Get language from user metadata or browser
    const getUserLanguage = async () => {
      // Try to get from user profile first (if implemented)
      const browserLanguage = navigator.language.startsWith('zh') ? 'zh' : 'en'
      setCurrentLanguage(browserLanguage)
    }
    
    getUserLanguage()
  }, [])

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element
      if (!target.closest('[data-theme-toggle]')) {
        setIsOpen(false)
      }
    }

    if (isOpen) {
      document.addEventListener('click', handleClickOutside)
      return () => document.removeEventListener('click', handleClickOutside)
    }
  }, [isOpen])

  if (!mounted) {
    return (
      <Button
        variant="ghost"
        size="sm"
        className={cn("w-9 h-9 p-0", className)}
        disabled
      >
        <Monitor className="h-4 w-4" />
        <span className="sr-only">Loading theme...</span>
      </Button>
    )
  }

  const currentThemeOption = themeOptions.find(option => option.value === theme)
  const CurrentIcon = currentThemeOption?.icon || Monitor

  if (variant === 'button') {
    const nextTheme = theme === 'light' ? 'dark' : theme === 'dark' ? 'system' : 'light'
    
    return (
      <Button
        variant="ghost"
        size="sm"
        className={cn("w-9 h-9 p-0", className)}
        onClick={() => setTheme(nextTheme)}
        title={`Current: ${currentThemeOption?.label[currentLanguage] || 'System'}`}
      >
        <CurrentIcon className="h-4 w-4 transition-transform duration-200" />
        <span className="sr-only">
          Toggle theme (current: {currentThemeOption?.label[currentLanguage] || 'System'})
        </span>
      </Button>
    )
  }

  return (
    <div className="relative" data-theme-toggle>
      <Button
        variant="ghost"
        size="sm"
        className={cn(
          "h-9 gap-2 px-3",
          showLabel ? "w-auto" : "w-9 px-0",
          className
        )}
        onClick={() => setIsOpen(!isOpen)}
        aria-expanded={isOpen}
        aria-haspopup="menu"
      >
        <CurrentIcon className="h-4 w-4" />
        {showLabel && (
          <>
            <span className="text-sm">
              {currentThemeOption?.label[currentLanguage] || 'System'}
            </span>
            <ChevronDown className={cn(
              "h-3 w-3 transition-transform",
              isOpen && "rotate-180"
            )} />
          </>
        )}
        <span className="sr-only">Theme options</span>
      </Button>

      {isOpen && (
        <div className="absolute right-0 top-full mt-1 w-36 rounded-md border border-border bg-popover p-1 shadow-md z-50">
          {themeOptions.map((option) => {
            const Icon = option.icon
            const isSelected = theme === option.value
            
            return (
              <button
                key={option.value}
                className={cn(
                  "w-full flex items-center gap-2 px-2 py-1.5 text-sm rounded-sm transition-colors",
                  "hover:bg-accent hover:text-accent-foreground",
                  "focus:bg-accent focus:text-accent-foreground focus:outline-none",
                  isSelected && "bg-accent text-accent-foreground"
                )}
                onClick={() => {
                  setTheme(option.value)
                  setIsOpen(false)
                }}
                role="menuitem"
              >
                <Icon className="h-4 w-4" />
                <span>{option.label[currentLanguage]}</span>
                {isSelected && (
                  <div className="ml-auto w-1 h-1 rounded-full bg-current" />
                )}
              </button>
            )
          })}
        </div>
      )}
    </div>
  )
}

// Simplified version for mobile menu
export function MobileThemeToggle({ className }: { className?: string }) {
  const { theme, setTheme } = useTheme()
  const [mounted, setMounted] = useState(false)
  const [currentLanguage, setCurrentLanguage] = useState<'en' | 'zh'>('en')

  useEffect(() => {
    setMounted(true)
    const browserLanguage = navigator.language.startsWith('zh') ? 'zh' : 'en'
    setCurrentLanguage(browserLanguage)
  }, [])

  if (!mounted) {
    return null
  }

  return (
    <div className={cn("space-y-1", className)}>
      <div className="text-sm font-medium text-muted-foreground px-3 py-2">
        {currentLanguage === 'zh' ? '主题' : 'Theme'}
      </div>
      {themeOptions.map((option) => {
        const Icon = option.icon
        const isSelected = theme === option.value
        
        return (
          <button
            key={option.value}
            className={cn(
              "w-full flex items-center gap-3 px-3 py-2 text-sm rounded-md transition-colors",
              "hover:bg-accent hover:text-accent-foreground",
              isSelected && "bg-accent text-accent-foreground"
            )}
            onClick={() => setTheme(option.value)}
          >
            <Icon className="h-4 w-4" />
            <span>{option.label[currentLanguage]}</span>
          </button>
        )
      })}
    </div>
  )
}