'use client'

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Languages, Check } from 'lucide-react'

interface LanguageToggleProps {
  variant?: 'dropdown' | 'button'
  showLabel?: boolean
}

export function LanguageToggle({ variant = 'dropdown', showLabel = true }: LanguageToggleProps) {
  const t = useTranslations('common')
  const [currentLocale, setCurrentLocale] = useState<string>('en')
  const [dropdownOpen, setDropdownOpen] = useState(false)

  const languages = [
    { code: 'en', name: 'English', nativeName: 'English' },
    { code: 'zh', name: 'Chinese', nativeName: '中文' }
  ]

  useEffect(() => {
    // Get current locale from cookie
    const localeCookie = document.cookie
      .split('; ')
      .find(row => row.startsWith('locale='))
      ?.split('=')[1];
    
    if (localeCookie) {
      setCurrentLocale(localeCookie)
    }
  }, [])

  const changeLanguage = (locale: string) => {
    // Clear existing locale cookie first
    document.cookie = `locale=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; samesite=lax`
    
    // Set new locale cookie
    document.cookie = `locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`
    
    // Force reload to apply new locale
    window.location.href = window.location.href
  }

  if (variant === 'button') {
    return (
      <Button
        variant="ghost"
        size="sm"
        onClick={() => {
          const nextLocale = currentLocale === 'en' ? 'zh' : 'en'
          changeLanguage(nextLocale)
        }}
        className="h-9 w-9 px-0"
      >
        <Languages className="h-4 w-4" />
        <span className="sr-only">{t('language')}</span>
      </Button>
    )
  }

  return (
    <div className="relative">
      <Button
        variant="ghost"
        size="sm"
        onClick={() => setDropdownOpen(!dropdownOpen)}
        className="h-9 gap-2"
      >
        <Languages className="h-4 w-4" />
        {showLabel && <span className="hidden sm:inline">{t('language')}</span>}
      </Button>

      {dropdownOpen && (
        <>
          <div
            className="fixed inset-0 z-40"
            onClick={() => setDropdownOpen(false)}
          />
          <div className="absolute right-0 top-full z-50 mt-2 w-48 rounded-md border bg-popover p-1 text-popover-foreground shadow-md">
            {languages.map((language) => (
              <button
                key={language.code}
                onClick={() => {
                  changeLanguage(language.code)
                  setDropdownOpen(false)
                }}
                className="relative flex w-full items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
              >
                <span className="flex-1 text-left">
                  {language.nativeName}
                </span>
                {currentLocale === language.code && (
                  <Check className="h-4 w-4" />
                )}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  )
}

export function MobileLanguageToggle() {
  const t = useTranslations('common')
  const [currentLocale, setCurrentLocale] = useState<string>('en')

  const languages = [
    { code: 'en', name: 'English', nativeName: 'English' },
    { code: 'zh', name: 'Chinese', nativeName: '中文' }
  ]

  useEffect(() => {
    // Get current locale from cookie
    const localeCookie = document.cookie
      .split('; ')
      .find(row => row.startsWith('locale='))
      ?.split('=')[1];
    
    if (localeCookie) {
      setCurrentLocale(localeCookie)
    }
  }, [])

  const changeLanguage = (locale: string) => {
    // Clear existing locale cookie first
    document.cookie = `locale=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; samesite=lax`
    
    // Set new locale cookie
    document.cookie = `locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`
    
    // Force reload to apply new locale
    window.location.href = window.location.href
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2 px-3 py-2">
        <Languages className="h-4 w-4" />
        <span className="text-sm font-medium">{t('language')}</span>
      </div>
      <div className="grid grid-cols-2 gap-2">
        {languages.map((language) => (
          <Button
            key={language.code}
            variant={currentLocale === language.code ? "default" : "outline"}
            size="sm"
            onClick={() => changeLanguage(language.code)}
            className="justify-start"
          >
            {language.nativeName}
          </Button>
        ))}
      </div>
    </div>
  )
}