"use client";

import Image from "next/image";
import { useEffect, useState } from "react";

export default function ThemeSwitcher() {
  const [isDark, setIsDark] = useState(false);
  const [mounted, setMounted] = useState(false);

  // بررسی تم در ابتدا
  useEffect(() => {
    const checkTheme = () => {
      const storedTheme = localStorage.getItem("theme");
      const isDarkMode = storedTheme === "dark" || 
        (storedTheme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
      setIsDark(isDarkMode);
    };
    
    checkTheme();
    setMounted(true);
    
    // گوش دادن به تغییرات تم در سایر تب‌ها
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "theme") {
        checkTheme();
      }
    };
    
    window.addEventListener("storage", handleStorageChange);
    return () => window.removeEventListener("storage", handleStorageChange);
  }, []); // آرایه خالی - فقط یک بار اجرا شود

  // گوش دادن به تغییرات سیستم (prefers-color-scheme)
  useEffect(() => {
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    
    const handleSystemThemeChange = (e: MediaQueryListEvent) => {
      const storedTheme = localStorage.getItem("theme");
      if (storedTheme === "system") {
        setIsDark(e.matches);
      }
    };
    
    mediaQuery.addEventListener("change", handleSystemThemeChange);
    return () => mediaQuery.removeEventListener("change", handleSystemThemeChange);
  }, []);

  const toggleTheme = () => {
    const currentTheme = localStorage.getItem("theme") || "system";
    let newTheme: string;
    
    if (currentTheme === "light") {
      newTheme = "dark";
    } else if (currentTheme === "dark") {
      newTheme = "system";
    } else {
      newTheme = "light";
    }
    
    localStorage.setItem("theme", newTheme);
    
    // بروزرسانی state
    if (newTheme === "dark") {
      setIsDark(true);
    } else if (newTheme === "light") {
      setIsDark(false);
    } else {
      // system
      const isSystemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
      setIsDark(isSystemDark);
    }
    
    // اعمال کلاس به html
    if (newTheme === "dark") {
      document.documentElement.classList.add("dark");
    } else if (newTheme === "light") {
      document.documentElement.classList.remove("dark");
    } else {
      // system
      if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }
    }
    
    // dispatch event برای هماهنگی با سایر کامپوننت‌ها
    window.dispatchEvent(new StorageEvent("storage", { key: "theme", newValue: newTheme }));
  };

  if (!mounted) {
    return null;
  }

  return (
    <div>
      <button onClick={toggleTheme}>
        {isDark === true ? (
          <div className="flex items-center gap-2">
            <Image
              width={24}
              height={24}
              alt={"sun icon"}
              src={`/images/icons/sun.svg`}
              className="dark:invert"
            />
            <span>تم روشن</span>
          </div>
        ) : (
          <div className="flex items-center gap-2">
            <Image
              width={24}
              height={24}
              alt={"moon icon"}
              src={`/images/icons/moon.svg`}
              className="dark:invert"
            />
            <span>تم تیره</span>
          </div>
        )}
      </button>
    </div>
  );
}