'use client';

import { useEffect, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { handleSetLocale } from '@/lib/actions';
import { Languages } from 'lucide-react';

type Translation = {
  language: string;
  languageSwitcher: string;
  english: string;
  arabic: string;
};

type Props = {
  t: Translation;
  currentLocale: string;
};

export function CompactLanguageSwitcher({ t, currentLocale }: Props) {
  const [isPending, startTransition] = useTransition();
  const [mounted, setMounted] = useState(false);
  const router = useRouter();

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return (
      <Button variant="ghost" size="icon" disabled aria-hidden="true">
        <Languages className="h-5 w-5" />
      </Button>
    );
  }

  const onSelectLocale = (locale: 'en' | 'ar') => {
    startTransition(async () => {
      await handleSetLocale(locale);
      router.refresh();
    });
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="icon" disabled={isPending}>
            <Languages className="h-5 w-5" />
            <span className="sr-only">{t.languageSwitcher}</span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuLabel>{t.language}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuItem 
            onSelect={() => onSelectLocale('en')} 
            disabled={isPending || currentLocale === 'en'}
        >
          {t.english}
        </DropdownMenuItem>
        <DropdownMenuItem 
            onSelect={() => onSelectLocale('ar')}
            disabled={isPending || currentLocale === 'ar'}
        >
          {t.arabic}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
