'use client';

import { useEffect, useState } from 'react';
import { Moon, Sun } from 'lucide-react';

type Theme = 'light' | 'dark';

export default function DarkModeToggle() {
  const [isDark, setIsDark] = useState(false);
  const [isMounted, setIsMounted] = useState(false);

  // Initialize theme from localStorage and system preference
  useEffect(() => {
    setIsMounted(true);

    // Check localStorage first, then system preference
    const savedTheme = localStorage.getItem('theme') as Theme | null;
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

    const shouldBeDark = savedTheme ?  savedTheme === 'dark' : prefersDark;

    setIsDark(shouldBeDark);
    updateTheme(shouldBeDark);
  }, []);

  // Update theme when isDark changes
  useEffect(() => {
    if (isMounted) {
      updateTheme(isDark);
    }
  }, [isDark, isMounted]);

  const updateTheme = (dark: boolean) => {
    const htmlElement = document.documentElement;
    const theme:  Theme = dark ? 'dark' : 'light';

    if (dark) {
      htmlElement.classList.add('dark');
    } else {
      htmlElement. classList.remove('dark');
    }

    localStorage.setItem('theme', theme);
    // Optional: Dispatch custom event for other components to listen to
    window.dispatchEvent(
      new CustomEvent('themechange', { detail: { theme } })
    );
  };

  const toggleTheme = () => {
    setIsDark((prev) => !prev);
  };

  // Prevent hydration mismatch
  if (! isMounted) {
    return (
      <button
        disabled
        className="flex items-center justify-center w-11 min-w-11 h-11 p-2 rounded-lg bg-gray-100 dark:bg-background max-md:p-1 max-xl:min-w-fit max-md:w-7 max-md:h-7 max-md:rounded-md opacity-50"
        aria-label="Toggle dark mode"
      />
    );
  }

  return (
    <button
      onClick={toggleTheme}
      className="flex items-center justify-center w-11 min-w-11 h-11 p-2 rounded-lg bg-gray-100 dark:bg-background max-md:p-1 max-xl:min-w-fit max-md:w-7 max-md:h-7 max-md:rounded-md transition-all duration-300 hover:bg-primary400 group dark:hover:bg-primary300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary400 dark:focus:ring-primary300"
      aria-label={`Switch to ${isDark ? 'light' : 'dark'} mode`}
      title={`Current theme: ${isDark ? 'dark' : 'light'}`}
    >
      {isDark ? (
        <Sun
          className="w-5 h-5 text-white group-hover:text-white transition-transform duration-300 group-hover:rotate-90"
          aria-hidden="true"
        />
      ) : (
        <Moon
          className="w-5 h-5 text-gray-900 group-hover:text-white transition-transform duration-300"
          aria-hidden="true"
        />
      )}
    </button>
  );
}