"use client";

import { Languages } from "lucide-react";
import { usePathname } from "next/navigation";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { AppLocale, getLocalizedPath, stripLocalePrefix } from "@/lib/locale";
import { cn } from "@/lib/utils";

type LocaleToggleProps = {
  locale: string;
  className?: string;
  showLabel?: boolean;
};

export function LocaleToggle({ locale, className, showLabel = false }: LocaleToggleProps) {
  const pathname = usePathname();
  const locales: AppLocale[] = ["de", "en", "ar"];
  const currentPath = stripLocalePrefix(pathname);
  const currentLocale = (["de", "en", "ar"].includes(locale) ? locale : "de") as AppLocale;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          type="button"
          variant="ghost"
          size={showLabel ? "sm" : "icon"}
          aria-label={`Locale: ${currentLocale.toUpperCase()}`}
          className={cn(
            "rounded-pill border border-transparent text-muted-foreground hover:border-border/70 hover:bg-background/80 hover:text-foreground",
            showLabel ? "gap-2 px-3" : undefined,
            className,
          )}
        >
          <Languages className="h-4 w-4" />
          {showLabel ? <span className="text-xs font-semibold uppercase tracking-[0.22em]">{currentLocale}</span> : null}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="min-w-[8rem]">
        {locales.map((targetLocale) => (
          <DropdownMenuItem key={targetLocale} asChild>
            <a
              href={getLocalizedPath(targetLocale, currentPath)}
              className="flex items-center justify-between gap-4"
            >
              <span>{targetLocale.toUpperCase()}</span>
              {targetLocale === currentLocale ? (
                <span className="text-xs text-muted-foreground">Active</span>
              ) : null}
            </a>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
