"use client";

import Image from "next/image";
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";

const PENDING_TOAST_STORAGE_KEY = "mohfarawati-pending-toast";

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

const localeChangedMessages: Record<AppLocale, string> = {
  de: "Sprache auf Deutsch gewechselt",
  en: "Language changed to English",
  ar: "تم تغيير اللغة إلى العربية",
};

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;
  const availableLocales = locales.filter((targetLocale) => targetLocale !== currentLocale);
  const contentFontClassName = currentLocale === "ar" ? "font-arabic" : "font-latin";
  const localeFlags: Record<AppLocale, { src: string; alt: string }> = {
    de: { src: "/flags/de.svg", alt: "German" },
    en: { src: "/flags/us.svg", alt: "English" },
    ar: { src: "/flags/sy.svg", alt: "Arabic" },
  };

  return (
    <DropdownMenu modal={false}>
      <DropdownMenuTrigger asChild>
        <Button
          type="button"
          variant="ghost"
          size={showLabel ? "sm" : "icon"}
          aria-label={`Locale: ${currentLocale.toUpperCase()}`}
          className={cn(
            "group inline-flex shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-full border border-transparent text-muted-foreground hover:border-border/70 hover:bg-background/80 hover:text-foreground",
            showLabel ? "h-9 w-9 p-0" : "h-9 w-9 p-0",
            className,
          )}
        >
          <Image
            src={localeFlags[currentLocale].src}
            alt={localeFlags[currentLocale].alt}
            width={20}
            height={20}
            className="h-5 w-5 shrink-0 rounded-full object-cover transition-transform duration-300 ease-out group-hover:scale-110"
          />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align="center"
        sideOffset={8}
        className={cn("w-12 min-w-12 p-1", contentFontClassName)}
      >
        {availableLocales.map((targetLocale) => (
          <DropdownMenuItem
            key={targetLocale}
            asChild
            className={cn(
              "cursor-pointer justify-center p-0",
              targetLocale === "ar" ? "font-arabic" : "font-latin",
            )}
          >
            <a
              href={getLocalizedPath(targetLocale, currentPath)}
              onClick={() => {
                const message = localeChangedMessages[targetLocale];

                if (!message) {
                  return;
                }

                window.sessionStorage.setItem(
                  PENDING_TOAST_STORAGE_KEY,
                  JSON.stringify({
                    type: "success",
                    message,
                    targetLocale,
                  }),
                );
              }}
              className="group flex h-10 w-10 items-center justify-center rounded-full"
            >
              <Image
                src={localeFlags[targetLocale].src}
                alt={localeFlags[targetLocale].alt}
                width={20}
                height={20}
                className="h-5 w-5 shrink-0 rounded-full object-cover transition-transform duration-300 ease-out group-hover:scale-110"
              />
            </a>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
