import * as Flags from 'country-flag-icons/react/3x2';
import { Globe } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuCheckboxItem,
    DropdownMenuContent,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useLanguage, useTranslation } from '@/contexts/LanguageContext';
import { cn } from '@/lib/utils';

type FlagCode = keyof typeof Flags;

function FlagIcon({ code, className }: { code: string; className?: string }) {
    const FlagComponent = Flags[code as FlagCode];
    if (!FlagComponent) {
        return <Globe className={cn('h-4 w-4', className)} />;
    }
    return <FlagComponent className={cn('h-4 w-5 rounded-sm', className)} />;
}

interface Props {
    /** Tailwind variant for the trigger Button. Default: ghost. */
    variant?: 'ghost' | 'outline' | 'secondary';
    className?: string;
    /** Anchor edge of the dropdown. Default: end (right). */
    align?: 'start' | 'end';
}

/**
 * Flag-driven language picker built on shadcn DropdownMenu primitives — same
 * portal/keyboard/animation behaviour as ThemeToggle, NotificationBell, etc.
 * Used in the default theme header, the dashboard header, and the lagged
 * theme footer. Falls back to the Globe glyph if the country code doesn't
 * match a flag in country-flag-icons.
 */
export function LanguageSelector({ variant = 'ghost', className, align = 'end' }: Props) {
    const { t } = useTranslation();
    const { locale, availableLanguages, setLocale } = useLanguage();

    if (availableLanguages.length <= 1) {
        return null;
    }

    const current = availableLanguages.find((l) => l.code === locale);

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button
                    variant={variant}
                    size="icon"
                    aria-label={t('Select language')}
                    className={className}
                >
                    {current?.country_code ? (
                        <FlagIcon code={current.country_code} />
                    ) : (
                        <Globe className="h-4 w-4" />
                    )}
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align={align} className="min-w-[10rem]">
                {availableLanguages.map((language) => (
                    <DropdownMenuCheckboxItem
                        key={language.code}
                        checked={language.code === locale}
                        onCheckedChange={() => {
                            if (language.code !== locale) setLocale(language.code);
                        }}
                    >
                        <FlagIcon code={language.country_code ?? ''} className="me-2" />
                        <span>{language.native_name}</span>
                    </DropdownMenuCheckboxItem>
                ))}
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
