"use client";

import { useRef, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { usePathname, useRouter } from "@/i18n/navigation";
import { locales, localeNames, type Locale } from "@/i18n/routing";
import { Check, ChevronDown, Globe } from "lucide-react";
import { useTransition } from "react";
import { useClickOutside } from "@/hooks/useClickOutside";

const LOCALE_CODES: Record<Locale, string> = {
  en: "EN",
  ur: "UR",
  ar: "AR",
  hi: "HI",
};

interface LanguageSwitcherProps {
  variant?: "default" | "header";
}

export default function LanguageSwitcher({ variant = "default" }: LanguageSwitcherProps) {
  const t = useTranslations("common");
  const locale = useLocale() as Locale;
  const router = useRouter();
  const pathname = usePathname();
  const [isPending, startTransition] = useTransition();
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  useClickOutside(rootRef, () => setOpen(false), open);

  function onChange(newLocale: Locale) {
    setOpen(false);
    startTransition(() => {
      router.replace(pathname, { locale: newLocale });
    });
  }

  if (variant === "header") {
    return (
      <div ref={rootRef} className="relative">
        <button
          type="button"
          onClick={() => setOpen((value) => !value)}
          disabled={isPending}
          aria-expanded={open}
          aria-haspopup="listbox"
          aria-label={t("language")}
          className="inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-md px-2.5 text-sm font-medium text-[var(--text-muted)] transition-colors hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)]/35 disabled:cursor-not-allowed disabled:opacity-50"
        >
          <Globe className="h-4 w-4 shrink-0" aria-hidden />
          <span>{LOCALE_CODES[locale]}</span>
          <ChevronDown
            className={`h-3.5 w-3.5 shrink-0 text-[var(--text-faint)] transition-transform ${open ? "rotate-180" : ""}`}
            aria-hidden
          />
        </button>

        {open && (
          <div
            role="listbox"
            aria-label={t("language")}
          className="absolute end-0 top-[calc(100%+6px)] z-50 w-[min(16rem,calc(100vw-2rem))] overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] p-1 shadow-[0_12px_40px_rgba(0,0,0,0.45)]"
          >
            {locales.map((loc) => {
              const selected = loc === locale;
              return (
                <button
                  key={loc}
                  type="button"
                  role="option"
                  aria-selected={selected}
                  onClick={() => onChange(loc)}
                  className={`flex w-full cursor-pointer items-center justify-between gap-3 rounded-md px-3 py-2 text-sm transition-colors ${
                    selected
                      ? "bg-[var(--bg-hover)] text-[var(--text)]"
                      : "text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
                  }`}
                >
                  <span>{localeNames[loc]}</span>
                  {selected && <Check className="h-4 w-4 shrink-0 text-[var(--accent)]" />}
                </button>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="relative inline-flex">
      <Globe
        className="pointer-events-none absolute start-2.5 top-1/2 z-10 h-3.5 w-3.5 -translate-y-1/2 text-[var(--accent)]"
        aria-hidden
      />
      <select
        value={locale}
        onChange={(e) => onChange(e.target.value as Locale)}
        disabled={isPending}
        aria-label={t("language")}
        className="h-9 min-w-[7.5rem] cursor-pointer appearance-none rounded-full border border-[var(--border)] bg-[var(--bg-elevated)] ps-8 pe-8 text-[13px] font-medium leading-none text-[var(--text)] shadow-sm transition-all hover:border-[var(--accent)]/40 hover:bg-[var(--bg-surface)] focus:outline-none focus:ring-2 focus:ring-[var(--accent)]/35 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {locales.map((loc) => (
          <option key={loc} value={loc}>
            {localeNames[loc]}
          </option>
        ))}
      </select>
      <ChevronDown
        className="pointer-events-none absolute end-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--text-faint)]"
        aria-hidden
      />
    </div>
  );
}
