"use client";

import { useEffect, useState } from "react";

export type Theme = "light" | "dark" | "system";

export default function ThemeToggle() {
  const [theme, setTheme] = useState<Theme | null>(null);

  useEffect(() => {
    try {
      const stored = localStorage.getItem("theme") as Theme | null;
      if (stored === "light" || stored === "dark" || stored === "system") {
        setTheme(stored);
      } else {
        setTheme("system");
      }
    } catch (e) {
      setTheme("system");
    }
  }, []);

  const applyTheme = (targetTheme: Theme) => {
    const isDark =
      targetTheme === "dark" ||
      (targetTheme === "system" &&
        window.matchMedia("(prefers-color-scheme: dark)").matches);

    if (isDark) {
      document.documentElement.classList.add("dark");
      document.documentElement.setAttribute("data-theme", "dark");
    } else {
      document.documentElement.classList.remove("dark");
      document.documentElement.setAttribute("data-theme", "light");
    }
  };

  const toggleTheme = () => {
    if (theme === null) return;
    const themeCycle: Record<Theme, Theme> = {
      light: "dark",
      dark: "system",
      system: "light",
    };
    const nextTheme = themeCycle[theme];
    setTheme(nextTheme);

    try {
      localStorage.setItem("theme", nextTheme);
    } catch (e) {}

    applyTheme(nextTheme);
    window.dispatchEvent(new Event("theme-change"));
  };

  useEffect(() => {
    const handleSync = () => {
      try {
        const stored = localStorage.getItem("theme") as Theme | null;
        if (stored === "light" || stored === "dark" || stored === "system") {
          setTheme(stored);
        } else {
          setTheme("system");
        }
      } catch (e) {
        setTheme("system");
      }
    };
    window.addEventListener("theme-change", handleSync);
    return () => window.removeEventListener("theme-change", handleSync);
  }, []);

  useEffect(() => {
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    const handleSystemThemeChange = (e: MediaQueryListEvent) => {
      try {
        const stored = localStorage.getItem("theme");
        if (!stored || stored === "system") {
          if (e.matches) {
            document.documentElement.classList.add("dark");
            document.documentElement.setAttribute("data-theme", "dark");
          } else {
            document.documentElement.classList.remove("dark");
            document.documentElement.setAttribute("data-theme", "light");
          }
          window.dispatchEvent(new Event("theme-change"));
        }
      } catch (err) {}
    };

    if (mediaQuery.addEventListener) {
      mediaQuery.addEventListener("change", handleSystemThemeChange);
    } else {
      mediaQuery.addListener(handleSystemThemeChange);
    }

    return () => {
      if (mediaQuery.removeEventListener) {
        mediaQuery.removeEventListener("change", handleSystemThemeChange);
      } else {
        mediaQuery.removeListener(handleSystemThemeChange);
      }
    };
  }, []);

  if (theme === null) {
    return (
      <button
        type="button"
        aria-label="테마 전환"
        className="inline-flex h-8 w-20 items-center justify-center rounded border border-ink/20 p-1 text-ink opacity-70"
      >
        <span className="h-3 w-3 rounded-full bg-ink-mute/40 animate-pulse" />
      </button>
    );
  }

  const getLabel = () => {
    if (theme === "dark") return "DARK";
    if (theme === "system") return "AUTO";
    return "LIGHT";
  };

  const getTitle = () => {
    if (theme === "light") return "Switch to Dark Mode";
    if (theme === "dark") return "Switch to System Theme";
    return "Switch to Light Mode";
  };

  const getAriaLabel = () => {
    if (theme === "light") return "다크 모드로 전환";
    if (theme === "dark") return "시스템 설정 모드로 전환";
    return "라이트 모드로 전환";
  };

  return (
    <button
      type="button"
      onClick={toggleTheme}
      aria-label={getAriaLabel()}
      title={getTitle()}
      className="inline-flex h-8 items-center gap-1.5 rounded border border-ink/25 px-2.5 py-1 text-[0.7rem] font-semibold uppercase tracking-wider text-ink transition duration-200 hover:border-ink hover:bg-paper focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-vermillion"
    >
      {theme === "dark" && (
        <svg
          className="h-3.5 w-3.5 text-cobalt"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth="2"
          stroke="currentColor"
          aria-hidden="true"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z"
          />
        </svg>
      )}
      {theme === "light" && (
        <svg
          className="h-3.5 w-3.5 text-vermillion"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth="2"
          stroke="currentColor"
          aria-hidden="true"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M12 3v2.25m0 13.5V21m8.966-8.966h-2.25M4.284 12h-2.25m15.364 6.364l-1.591-1.591M6.758 6.758L5.167 5.167m12.728 0l-1.591 1.591M6.758 17.242l-1.591 1.591M12 7.5a4.5 4.5 0 100 9 4.5 4.5 0 000-9z"
          />
        </svg>
      )}
      {theme === "system" && (
        <svg
          className="h-3.5 w-3.5 text-ink-mute"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth="2"
          stroke="currentColor"
          aria-hidden="true"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25A2.25 2.25 0 015.25 3h13.5A2.25 2.25 0 0121 5.25z"
          />
        </svg>
      )}
      <span className="font-mono text-[0.68rem] uppercase text-ink">
        {getLabel()}
      </span>
    </button>
  );
}
