import { useRouterState } from "@tanstack/react-router";
import { Check, ChevronDown } from "lucide-react";
import Flag from "react-flagkit";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useT, langFromPath, stripLangPrefix, localizePath, SITE_URL, type Lang } from "@/lib/i18n";
import { cn } from "@/lib/utils";

/**
 * Language switcher with country flags (FlagKit through react-flagkit), in the
 * same shape as the switcher on highriskpayments.nl: an outline button showing
 * the flag plus the language code, opening a small menu with the language names.
 *
 * Switching is a full page load on purpose: the language lives in the path
 * (/en/...), so the server renders the whole page in the chosen language and the
 * URL stays shareable and indexable.
 *
 * Pass `inline` for the two-segment control the mobile drawer uses. The dropdown
 * portals into <body> at z-50 while the drawer overlay sits at z-60, so inside the
 * drawer the menu opened behind the backdrop: tapping a language actually hit the
 * backdrop and closed the menu. Plain links in the drawer have no such layer.
 */
const LANGUAGES: { code: Lang; country: string; label: string }[] = [
  { code: "nl", country: "NL", label: "Nederlands" },
  { code: "en", country: "GB", label: "English" },
];

export default function LanguageSwitch({
  className = "",
  inline = false,
  onSwitch,
}: {
  className?: string;
  inline?: boolean;
  /** Runs before the full page load, so a drawer can close itself first. */
  onSwitch?: () => void;
}) {
  const t = useT();
  const publicHref = useRouterState({ select: (s) => s.location.publicHref });
  const url = new URL(publicHref, SITE_URL);
  const current = langFromPath(url.pathname);
  const base = stripLangPrefix(url.pathname);
  const hrefFor = (language: Lang) => `${localizePath(base, language)}${url.search}${url.hash}`;
  const active = LANGUAGES.find((language) => language.code === current) ?? LANGUAGES[0]!;
  const label = t("Taal wijzigen", "Change language");

  if (inline) {
    return (
      <div
        role="group"
        aria-label={label}
        className={cn(
          "inline-flex items-center gap-1 rounded-full border border-shell-border bg-shell p-1",
          className,
        )}
      >
        {LANGUAGES.map((language) => {
          const isActive = current === language.code;
          const itemClass = cn(
            "inline-flex flex-1 items-center justify-center gap-2 rounded-full px-4 py-2.5 text-xs font-semibold uppercase tracking-wide transition-colors",
            isActive
              ? "bg-gradient-to-r from-brand-gold-lo to-brand-gold text-brand-gold-contrast"
              : "text-shell-foreground/70 hover:bg-shell-foreground/10 hover:text-brand-gold",
          );
          const content = (
            <>
              <Flag
                country={language.country}
                size={16}
                alt=""
                aria-hidden="true"
                className="rounded-[3px]"
              />
              <span aria-hidden="true">{language.code.toUpperCase()}</span>
            </>
          );

          return isActive ? (
            <span
              key={language.code}
              aria-current="true"
              aria-label={language.label}
              title={language.label}
              className={itemClass}
            >
              {content}
            </span>
          ) : (
            <a
              key={language.code}
              href={hrefFor(language.code)}
              hrefLang={language.code}
              aria-label={language.label}
              title={language.label}
              onClick={onSwitch}
              className={itemClass}
            >
              {content}
            </a>
          );
        })}
      </div>
    );
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          className={cn("gap-2 border-shell-border text-shell-foreground", className)}
          aria-label={label}
        >
          <Flag
            country={active.country}
            size={16}
            alt=""
            aria-hidden="true"
            className="rounded-[3px]"
          />
          <span className="text-xs font-semibold uppercase tracking-wide">{active.code}</span>
          <ChevronDown className="size-3.5 opacity-70" aria-hidden="true" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="z-[70] min-w-44">
        <div className="px-2 pt-1.5 pb-1 font-mono text-[10px] uppercase tracking-[0.2em] text-muted-foreground">
          {label}
        </div>
        <DropdownMenuSeparator />
        {LANGUAGES.map((language) => (
          <DropdownMenuItem key={language.code} asChild>
            <a
              href={hrefFor(language.code)}
              hrefLang={language.code}
              aria-current={current === language.code ? "true" : undefined}
              className="gap-2"
            >
              <Flag
                country={language.country}
                size={18}
                alt=""
                aria-hidden="true"
                className="rounded-[3px]"
              />
              {language.label}
              {current === language.code && (
                <Check className="ml-auto text-primary" aria-hidden="true" />
              )}
            </a>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
