import React from 'react';
import { usePage, router } from '@inertiajs/react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Globe, Check } from 'lucide-react';

export default function LanguageSwitcher() {
    // 1. Get current locale and list of active languages from Global Props
    const { locale, languages } = usePage().props;

    // 2. Safety Check: If no languages are configured or only 1 exists, hide the switcher
    if (!languages || languages.length < 2) {
        return null;
    }

    // 3. Handle Language Switch
    const handleSwitch = (code) => {
        router.post(route('locale.switch'), { locale: code }, {
            preserveScroll: true, // Keep user at same scroll position
            onFinish: () => {
                // Optional: If switching RTL/LTR causes complex layout shifts, 
                // you might want to force a reload here, but usually not needed.
            }
        });
    };

    // Find current language object for display (optional)
    const currentLang = languages.find(l => l.code === locale);

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="rounded-full w-9 h-9" title="Switch Language">
                    <Globe className="h-[1.2rem] w-[1.2rem] transition-transform hover:scale-110" />
                    <span className="sr-only">Switch Language</span>
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="min-w-[120px]">
                {languages.map((lang) => (
                    <DropdownMenuItem 
                        key={lang.code} 
                        onClick={() => handleSwitch(lang.code)}
                        className="justify-between cursor-pointer"
                    >
                        <span className="uppercase text-xs font-bold mr-2 text-muted-foreground w-6">
                            {lang.code}
                        </span>
                        <span className="flex-1 truncate">
                            {lang.name}
                        </span>
                        
                        {/* Active Checkmark */}
                        {locale === lang.code && (
                            <Check className="h-3.5 w-3.5 text-primary ml-2" />
                        )}
                    </DropdownMenuItem>
                ))}
            </DropdownMenuContent>
        </DropdownMenu>
    );
}