"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useTheme } from "@/lib/theme/theme-provider";
import { useLocale, LOCALE_LABELS, type AppLocale } from "@/lib/i18n";
import { tc } from "@/lib/i18n/common-labels";
import { useAppConfig } from "@/lib/settings/useAppConfig";
import { isDarkModeEnabled, filterLanguageOptions } from "@/lib/settings/validators";
import { api } from "@/lib/api-client";
import type { ThemeOption } from "@/lib/api-types";

const SunIcon = () => (
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
    <circle cx="8" cy="8" r="3" />
    <path d="M8 1.5v1M8 13.5v1M1.5 8h1M13.5 8h1M3.4 3.4l.7.7M11.9 11.9l.7.7M3.4 12.6l.7-.7M11.9 4.1l.7-.7" />
  </svg>
);

const MoonIcon = () => (
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M13.5 8.5a5.5 5.5 0 0 1-7-7 5.5 5.5 0 1 0 7 7z" />
  </svg>
);

const MonitorIcon = () => (
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    <rect x="1.5" y="2" width="13" height="9" rx="1.5" />
    <path d="M5.5 14h5M8 11v3" />
  </svg>
);

const THEME_ICONS: Record<ThemeOption, typeof SunIcon> = {
  light: SunIcon,
  dark: MoonIcon,
  system: MonitorIcon,
};

export default function AppSettingsControl() {
  const { theme, setTheme } = useTheme();
  const { locale, setLocale } = useLocale();
  const { config } = useAppConfig();
  const [open, setOpen] = useState(false);
  const popoverRef = useRef<HTMLDivElement>(null);

  const darkEnabled = isDarkModeEnabled(config);
  const allowedThemes = (config?.appearance?.allowedThemes ?? ["light", "dark", "system"]).filter(
    (t): t is ThemeOption => darkEnabled || t !== "dark",
  );
  const languages = filterLanguageOptions(config?.languages ?? ["uz", "ru", "en"]);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const handleLocaleChange = useCallback(
    (next: AppLocale) => {
      setLocale(next);
      document.documentElement.lang = next;
      api.farmer.updatePreferences({ primaryLanguage: next }).catch(() => {});
    },
    [setLocale],
  );

  return (
    <div className="relative" ref={popoverRef}>
      <button
        onClick={() => setOpen((v) => !v)}
        className="flex items-center gap-1.5 rounded-full px-3 py-2 text-sm font-semibold
                   bg-[var(--glass)] border border-[var(--border)]
                   hover:bg-[var(--glass-strong)] transition-colors"
        aria-label={tc("settings", locale)}
        aria-expanded={open}
      >
        {(() => { const Icon = THEME_ICONS[theme]; return <Icon />; })()}
        <span className="hidden sm:inline">{LOCALE_LABELS[locale]}</span>
      </button>

      {open && (
        <div
          className="absolute right-0 top-full mt-2 z-50 w-56 rounded-2xl p-3 space-y-3
                     bg-[var(--surface)] border border-[var(--border)]
                     shadow-lg backdrop-blur-xl"
          role="dialog"
          aria-label={tc("settings", locale)}
        >
          {/* Theme selector */}
          <div>
            <div className="text-xs font-bold uppercase tracking-wider text-[var(--muted)] mb-1.5">
              {tc("theme", locale)}
            </div>
            <div className="flex gap-1 rounded-xl bg-[var(--glass)] p-1">
              {allowedThemes.map((t) => {
                const Icon = THEME_ICONS[t];
                const active = theme === t;
                return (
                  <button
                    key={t}
                    onClick={() => setTheme(t)}
                    aria-pressed={active}
                    className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-xs font-semibold transition-colors
                      ${active
                        ? "bg-[var(--surface)] text-[var(--ink)] shadow-sm"
                        : "text-[var(--muted)] hover:text-[var(--ink)]"}`}
                  >
                    <Icon />
                    {tc(t, locale)}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Language selector */}
          <div>
            <div className="text-xs font-bold uppercase tracking-wider text-[var(--muted)] mb-1.5">
              {tc("language", locale)}
            </div>
            <div className="flex flex-col gap-0.5">
              {languages.map((lang) => (
                <button
                  key={lang}
                  onClick={() => handleLocaleChange(lang)}
                  className={`rounded-lg px-3 py-1.5 text-left text-sm font-medium transition-colors
                    ${locale === lang
                      ? "bg-[var(--green)]/10 text-[var(--green-deep)]"
                      : "text-[var(--ink-soft)] hover:bg-[var(--glass)]"}`}
                >
                  {LOCALE_LABELS[lang]}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
