import React, { useState, useEffect } from 'react';
import { getCurrentTheme, toggleTheme as toggleThemeUtil } from '../lib/theme';

// Extend Window interface for theme events
declare global {
  interface Window {
    __INITIAL_THEME__?: 'light' | 'dark';
  }
  interface WindowEventMap {
    'themeChanged': CustomEvent<{ theme: 'light' | 'dark' }>;
  }
}

interface ThemeToggleProps {
  className?: string;
}

export default function ThemeToggle({ className = '' }: ThemeToggleProps) {
  const [theme, setTheme] = useState<'light' | 'dark'>('dark');
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    
    // Get current theme - use the initial theme if available
    const currentTheme = window.__INITIAL_THEME__ || getCurrentTheme();
    setTheme(currentTheme);
    
    // Listen for theme changes
    const handleThemeChange = (e: CustomEvent<{ theme: 'light' | 'dark' }>) => {
      setTheme(e.detail.theme);
    };
    
    window.addEventListener('themeChanged', handleThemeChange);
    
    return () => {
      window.removeEventListener('themeChanged', handleThemeChange);
    };
  }, []);

  const handleToggle = () => {
    const newTheme = toggleThemeUtil();
    setTheme(newTheme);
  };

  // Don't render until mounted to avoid hydration mismatch
  if (!mounted) {
    return (
      <button 
        disabled 
        className={`px-3 py-2 rounded-lg cursor-not-allowed opacity-50 ${className}`}
        style={{
          background: 'var(--glass-bg-button)',
          color: 'var(--glass-text-tertiary)',
          border: '1px solid var(--glass-border)',
        }}
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <circle cx="12" cy="12" r="5"/>
          <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/>
        </svg>
      </button>
    );
  }

  return (
    <button
      onClick={handleToggle}
      className={`px-3 py-2 rounded-lg transition-all duration-200 hover:scale-105 ${className}`}
      style={{
        background: 'var(--glass-bg-button)',
        color: 'var(--glass-text-primary)',
        border: '1px solid var(--glass-border)',
      }}
      title={`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}
      aria-label={`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}
    >
      {theme === 'light' ? (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
        </svg>
      ) : (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
        </svg>
      )}
    </button>
  );
}