"use client";

import { Globe } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useI18n, type Locale } from "@/lib/i18n";

const languages: { value: Locale; label: string; flag: string }[] = [
  { value: "en", label: "English", flag: "🇬🇧" },
  { value: "fr", label: "Français", flag: "🇫🇷" },
  { value: "es", label: "Español", flag: "🇪🇸" },
  { value: "de", label: "Deutsch", flag: "🇩🇪" },
  { value: "pt", label: "Português", flag: "🇧🇷" },
  { value: "it", label: "Italiano", flag: "🇮🇹" },
  { value: "nl", label: "Nederlands", flag: "🇳🇱" },
  { value: "ru", label: "Русский", flag: "🇷🇺" },
  { value: "ja", label: "日本語", flag: "🇯🇵" },
  { value: "ko", label: "한국어", flag: "🇰🇷" },
  { value: "zh", label: "中文", flag: "🇨🇳" },
  { value: "ar", label: "العربية", flag: "🇸🇦" },
  { value: "fa", label: "فارسی", flag: "🇮🇷" },
];

interface LanguageSwitcherProps {
  variant?: "select" | "button";
}

export function LanguageSwitcher({ variant = "select" }: LanguageSwitcherProps) {
  const { locale, setLocale } = useI18n();

  if (variant === "button") {
    const currentIndex = languages.findIndex((l) => l.value === locale);
    const nextIndex = (currentIndex + 1) % languages.length;
    const nextLang = languages[nextIndex];
    const currentLang = languages[currentIndex];

    return (
      <Button
        variant="ghost"
        size="sm"
        onClick={() => setLocale(nextLang.value)}
        className="gap-1.5 text-muted-foreground hover:text-foreground"
      >
        <Globe className="h-4 w-4" />
        <span className="text-sm">{currentLang.flag}</span>
        <span className="text-xs font-medium uppercase">{currentLang.value}</span>
      </Button>
    );
  }

  return (
    <Select value={locale} onValueChange={(v) => setLocale(v as Locale)}>
      <SelectTrigger className="w-[150px] h-9">
        <SelectValue>
          <span className="flex items-center gap-2">
            <Globe className="h-4 w-4" />
            {languages.find((l) => l.value === locale)?.flag}{" "}
            {languages.find((l) => l.value === locale)?.label}
          </span>
        </SelectValue>
      </SelectTrigger>
      <SelectContent>
        {languages.map((lang) => (
          <SelectItem
            key={lang.value}
            value={lang.value}
          >
            <span className="flex items-center gap-2">
              <span>{lang.flag}</span>
              <span>{lang.label}</span>
            </span>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
