import React, { useCallback } from 'react';
import { usePage } from '@inertiajs/react';
import { Link, router } from '@inertiajs/react';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
import { useAppearance } from '@/hooks/use-appearance';
import { useLocalizedRoutes } from '@/hooks/useLocalizedRoutes';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Sun, Moon } from 'lucide-react';
import { cn } from '@/lib/utils';

const Header: React.FC = () => {
  const { auth } = usePage().props as any;
  const { t } = useTranslation('auth');
  const { appearance, updateAppearance } = useAppearance();
  const { localizedPath } = useLocalizedRoutes();

  const toggleTheme = () => {
    const newAppearance = appearance === 'dark' ? 'light' : 'dark';
    updateAppearance(newAppearance);
  };

  const handleLanguageChange = useCallback(async (value: string) => {
    console.log('handleLanguageChange called with:', value);
    try {
      const response = await fetch('/set-locale', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
        },
        body: JSON.stringify({ locale: value }),
      });

      console.log('fetch response:', response.status);
      if (response.ok) {
        console.log('calling i18n.changeLanguage with:', value);
        i18n.changeLanguage(value);
        // Reload only the locale prop to update the page props
        router.reload({ only: ['locale'] });
      }
    } catch (error) {
      console.error('Failed to change locale:', error);
    }
  }, []);

  const handleLogout = () => {
    router.post('/logout');
  };

  return (
    <header className="fixed top-0 z-50 w-full bg-white dark:bg-gray-900 shadow-lg border-b-2 border-gray-200 dark:border-gray-700">
      <div className="container mx-auto px-4 py-4">
        <div className="flex justify-between items-center">
          <Link href="{localizedPath('/')}" className="text-2xl font-bold text-gray-800 dark:text-gray-200">
            Fotospiel
          </Link>
          <nav className="flex space-x-8">
            <Button asChild variant="ghost" className="text-gray-700 hover:text-pink-600 hover:bg-pink-50 dark:text-gray-300 dark:hover:text-pink-400 dark:hover:bg-pink-950/20 font-sans-marketing text-lg font-medium transition-all duration-200">
              <Link href={localizedPath('/')}>
                {t('header.home', 'Home')}
              </Link>
            </Button>
            <Button asChild variant="ghost" className="text-gray-700 hover:text-pink-600 hover:bg-pink-50 dark:text-gray-300 dark:hover:text-pink-400 dark:hover:bg-pink-950/20 font-sans-marketing text-lg font-medium transition-all duration-200">
              <Link href={localizedPath('/packages')}>
                {t('header.packages', 'Pakete')}
              </Link>
            </Button>
            <Button asChild variant="ghost" className="text-gray-700 hover:text-pink-600 hover:bg-pink-50 dark:text-gray-300 dark:hover:text-pink-400 dark:hover:bg-pink-950/20 font-sans-marketing text-lg font-medium transition-all duration-200">
              <Link href={localizedPath('/blog')}>
                {t('header.blog', 'Blog')}
              </Link>
            </Button>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="text-gray-700 hover:text-pink-600 hover:bg-pink-50 dark:text-gray-300 dark:hover:text-pink-400 dark:hover:bg-pink-950/20 font-sans-marketing text-lg font-medium transition-all duration-200">
                  Anlässe
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <DropdownMenuItem asChild>
                  <Link href={localizedPath('/anlaesse/hochzeit')} className="w-full flex items-center">
                    {t('header.occasions.wedding', 'Hochzeit')}
                  </Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild>
                  <Link href={localizedPath('/anlaesse/geburtstag')} className="w-full flex items-center">
                    {t('header.occasions.birthday', 'Geburtstag')}
                  </Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild>
                  <Link href={localizedPath('/anlaesse/firmenevent')} className="w-full flex items-center">
                    {t('header.occasions.corporate', 'Firmenevent')}
                  </Link>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
            <Button asChild variant="ghost" className="text-gray-700 hover:text-pink-600 hover:bg-pink-50 dark:text-gray-300 dark:hover:text-pink-400 dark:hover:bg-pink-950/20 font-sans-marketing text-lg font-medium transition-all duration-200">
              <Link href={localizedPath('/kontakt')}>
                {t('header.contact', 'Kontakt')}
              </Link>
            </Button>
          </nav>
          <div className="flex items-center space-x-4">
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleTheme}
              className="h-8 w-8"
            >
              <Sun className={cn("h-4 w-4", appearance === "dark" && "hidden")} />
              <Moon className={cn("h-4 w-4", appearance !== "dark" && "hidden")} />
              <span className="sr-only">Theme Toggle</span>
            </Button>
            <Select value={i18n.language || 'de'} onValueChange={handleLanguageChange}>
              <SelectTrigger className="w-[70px] h-8">
                <SelectValue placeholder="DE" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="de">DE</SelectItem>
                <SelectItem value="en">EN</SelectItem>
              </SelectContent>
            </Select>
            {auth.user ? (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="relative h-8 w-8 rounded-full">
                    <Avatar className="h-8 w-8">
                      <AvatarImage src={auth.user?.avatar} alt={auth.user?.name || 'User'} />
                      <AvatarFallback>{(auth.user?.name || auth.user?.email || 'U').charAt(0)}</AvatarFallback>
                    </Avatar>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-56" align="end" forceMount>
                  <DropdownMenuLabel className="font-normal">
                    <div className="flex flex-col space-y-1">
                      <p className="text-sm font-medium leading-none">{auth.user?.name || auth.user?.email || 'User'}</p>
                      <p className="text-xs leading-none text-muted-foreground">{auth.user?.email || ''}</p>
                    </div>
                  </DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem asChild>
                    <Link href={localizedPath('/profile')}>
                      Profil
                    </Link>
                  </DropdownMenuItem>
                  <DropdownMenuItem asChild>
                    <Link href={localizedPath('/profile/orders')}>
                      Bestellungen
                    </Link>
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={handleLogout}>
                    Abmelden
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            ) : (
              <>
                <Link
                  href={localizedPath('/login')}
                  className="text-gray-700 hover:text-pink-600 dark:text-gray-300 dark:hover:text-pink-400 font-medium transition-colors duration-200"
                >
                  {t('header.login')}
                </Link>
                <Link
                  href={localizedPath('/register')}
                  className="bg-pink-500 text-white px-4 py-2 rounded hover:bg-pink-600 dark:bg-pink-600 dark:hover:bg-pink-700"
                >
                  {t('header.register')}
                </Link>
              </>
            )}
          </div>
        </div>
      </div>
    </header>
  );
};

export default Header;