"use client";

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

export default function ThemeSwitcher() {
  const { t } = useTranslation("common");
  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);
  }, []);

  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);

    if (newTheme === "dark") {
      setIsDark(true);
    } else if (newTheme === "light") {
      setIsDark(false);
    } else {
      const isSystemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
      setIsDark(isSystemDark);
    }

    if (newTheme === "dark") {
      document.documentElement.classList.add("dark");
    } else if (newTheme === "light") {
      document.documentElement.classList.remove("dark");
    } else {
      if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }
    }

    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>{t("themeUi.light")}</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>{t("themeUi.dark")}</span>
          </div>
        )}
      </button>
    </div>
  );
}
