"use client";

import { useState, useTransition } from "react";
import { useRouter, usePathname } from "next/navigation";
import { Globe } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import type { Locale } from "@/lib/i18n/config";
import { cn } from "@/lib/utils";

const LABELS: Record<Locale, string> = { en: "English", pl: "Polski" };

export function LanguageSwitcher({
  currentLocale,
  isAuthenticated = false
}: {
  currentLocale: Locale;
  isAuthenticated?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [isPending, startTransition] = useTransition();
  const router = useRouter();
  const pathname = usePathname();

  function switchTo(locale: Locale) {
    setOpen(false);
    if (locale === currentLocale) return;

    document.cookie = `tidyly-locale=${locale};path=/;max-age=31536000`;

    // Persist to the user's profile if logged in, per spec section 5.
    if (isAuthenticated) {
      const supabase = createClient();
      supabase.auth.getUser().then(({ data }) => {
        if (data.user) {
          supabase.from("profiles").update({ preferred_language: locale }).eq("id", data.user.id);
        }
      });
    }

    const segments = pathname.split("/");
    segments[1] = locale;
    startTransition(() => {
      router.push(segments.join("/") || `/${locale}`);
      router.refresh();
    });
  }

  return (
    <div className="relative">
      <button
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        disabled={isPending}
        className="flex h-9 items-center gap-1.5 rounded-xl px-2.5 text-sm text-ink-600 hover:bg-ink-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
      >
        <Globe className="h-4 w-4" aria-hidden="true" />
        <span className="uppercase">{currentLocale}</span>
      </button>
      {open && (
        <ul
          role="listbox"
          className="absolute right-0 z-20 mt-1 w-36 overflow-hidden rounded-xl border border-ink-100 bg-white py-1 shadow-card"
        >
          {(Object.keys(LABELS) as Locale[]).map((locale) => (
            <li key={locale}>
              <button
                role="option"
                aria-selected={locale === currentLocale}
                onClick={() => switchTo(locale)}
                className={cn(
                  "flex w-full items-center px-3 py-2 text-left text-sm hover:bg-ink-50",
                  locale === currentLocale && "font-semibold text-brand-700"
                )}
              >
                {LABELS[locale]}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
