"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import styles from "./LanguageDropdown.module.css";
import { Locale, locales, resolveLocale, getLocaleDisplayName } from "@/config/i18n";
import { Icon } from "@/components/ui/Icon";

type LanguageDropdownProps = {
  locale?: Locale;
  menuLabel?: string;
};

export function LanguageDropdown({ locale: providedLocale, menuLabel }: LanguageDropdownProps) {
  const params = useParams() as { locale?: string };
  const pathname = usePathname();
  const currentLocale = providedLocale ?? resolveLocale(params?.locale);
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const label = menuLabel ?? "Select language";

  useEffect(() => {
    function handleClick(event: MouseEvent) {
      if (!containerRef.current) return;
      if (!containerRef.current.contains(event.target as Node)) {
        setOpen(false);
      }
    }
    if (open) {
      document.addEventListener("click", handleClick);
      return () => document.removeEventListener("click", handleClick);
    }
    return undefined;
  }, [open]);

  const segments = pathname.split("/").filter(Boolean);

  const getHref = (locale: Locale) => {
    if (segments[0] && locales.includes(segments[0] as Locale)) {
      const [, ...rest] = segments;
      return `/${locale}${rest.length ? `/${rest.join("/")}` : ""}`;
    }
    return `/${locale}${segments.length ? `/${segments.join("/")}` : ""}`;
  };

  return (
    <div className={styles.root} ref={containerRef}>
      <button
        type="button"
        className={styles.trigger}
        onClick={() => setOpen((prev) => !prev)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={label}
      >
        <Icon name="Globe" style={{ width: 16, height: 16 }} aria-hidden />
        {currentLocale.toUpperCase()}
        <span className={styles.caret} aria-hidden />
      </button>

      {open ? (
        <div className={styles.menu} role="listbox" aria-label={label}>
          {locales.map((locale) => (
            <Link
              key={locale}
              href={getHref(locale)}
              className={`${styles.item} ${locale === currentLocale ? styles.active : ""}`}
              onClick={() => setOpen(false)}
            >
              <span>{getLocaleDisplayName(locale, currentLocale)}</span>
              <span style={{ fontSize: "11px", opacity: 0.6 }}>{locale.toUpperCase()}</span>
            </Link>
          ))}
        </div>
      ) : null}
    </div>
  );
}
