"use client"
import Image from "next/image";
import { useEffect, useState } from "react";
import { icons } from "#/assets/icons"

export default function Theme() {

  const [theme, setTheme] = useState<string>(
    localStorage.getItem("theme") || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
  );

  useEffect(() => {
    document.body.setAttribute("data-theme", theme);
    localStorage.setItem("theme", theme);

    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    const handleChange = (e: MediaQueryListEvent) => {
      const newTheme = e.matches ? "dark" : "light";
      setTheme(newTheme);
    };

    mediaQuery.addEventListener("change", handleChange);

    return () => {
      mediaQuery.removeEventListener("change", handleChange);
    };
  }, [theme]);

  const handleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  return (
    <>
      <div onClick={() => handleTheme()} className="theme">
        <button type="button" className="icon-border">
          {theme === "light" ?
            <Image src={icons.sunIcon} alt="Light Mode" width={20} height={20} className="m-[2px]" />
            :
            <Image src={icons.moonIcon} alt="Dark Mode" width={20} height={20} className="m-[2px]" />
          }
        </button>
      </div>
    </>
  )
}