"use client";

import { useEffect, useState } from "react";

const THEME_KEY = "propertypilot-theme-v2";

type Theme = "homecare" | "light" | "black";

const themeOptions: Array<{ label: string; value: Theme }> = [
  { label: "HomeCare", value: "homecare" },
  { label: "Off-white", value: "light" },
  { label: "True black", value: "black" },
];

function applyTheme(theme: Theme) {
  document.documentElement.dataset.theme = theme;
  document.documentElement.style.colorScheme = theme === "light" ? "light" : "dark";
}

function getInitialTheme(): Theme {
  if (typeof window === "undefined") {
    return "homecare";
  }

  const stored = window.localStorage.getItem(THEME_KEY);

  if (stored === "homecare" || stored === "light" || stored === "black") {
    return stored;
  }

  return "homecare";
}

export function ThemeToggle() {
  const [theme, setTheme] = useState<Theme>("homecare");

  useEffect(() => {
    const animationFrame = window.requestAnimationFrame(() => {
      const initialTheme = getInitialTheme();

      setTheme(initialTheme);
      applyTheme(initialTheme);
    });

    return () => window.cancelAnimationFrame(animationFrame);
  }, []);

  function chooseTheme(nextTheme: Theme) {
    setTheme(nextTheme);
    window.localStorage.setItem(THEME_KEY, nextTheme);
    applyTheme(nextTheme);
  }

  return (
    <div
      aria-label="Appearance"
      className="grid gap-2 rounded-[18px] border border-border bg-surface-strong p-1.5 sm:grid-cols-3"
      role="group"
    >
      {themeOptions.map((option) => {
        const selected = theme === option.value;

        return (
          <button
            aria-pressed={selected}
            className={[
              "rounded-[14px] px-3 py-2 text-sm font-semibold transition",
              selected
                ? "bg-primary text-white shadow-sm"
                : "text-muted hover:bg-primary-soft hover:text-primary",
            ].join(" ")}
            key={option.value}
            onClick={() => chooseTheme(option.value)}
            type="button"
          >
            {option.label}
          </button>
        );
      })}
    </div>
  );
}

export function ThemeHydrator() {
  useEffect(() => {
    const animationFrame = window.requestAnimationFrame(() => {
      applyTheme(getInitialTheme());
    });

    return () => window.cancelAnimationFrame(animationFrame);
  }, []);

  return null;
}
