'use client';

import React, { useState, useRef, useEffect } from 'react';
import { useTheme } from 'next-themes';
import { SunIcon, MoonIcon, ContrastIcon, HighContrastLightIcon, HighContrastDarkIcon } from '../atoms/Icons';

type ThemeType = 'light' | 'dark' | 'high-contrast-light' | 'high-contrast-dark' | 'system';

const ThemeSelector: React.FC = () => {
  const { theme, setTheme, resolvedTheme } = useTheme();
  const [isOpen, setIsOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  
  // Prevent hydration mismatch
  useEffect(() => {
    setMounted(true);
  }, []);
  
  if (!mounted) {
    return (
      <div className="p-2 rounded-md text-gray-700 dark:text-white">
        <SunIcon size={20} />
      </div>
    );
  }
  
  // Simple close handler for escape key
  const handleKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === 'Escape') {
      setIsOpen(false);
    }
  };
  
  const handleThemeChange = (newTheme: ThemeType) => {
    setTheme(newTheme);
    setIsOpen(false);
  };
  
  // Get current theme icon based on resolved theme
  const ThemeIcon = () => {
    switch (resolvedTheme) {
      case 'dark':
        return <MoonIcon size={20} />;
      case 'high-contrast-light':
        return <HighContrastLightIcon size={20} />;
      case 'high-contrast-dark':
        return <HighContrastDarkIcon size={20} />;
      default:
        return <SunIcon size={20} />;
    }
  };
  
  // Get theme name for screen readers
  const getThemeName = (themeType: string | undefined): string => {
    switch (themeType) {
      case 'dark':
        return 'Dark Mode';
      case 'high-contrast-light':
        return 'High Contrast Light Mode';
      case 'high-contrast-dark':
        return 'High Contrast Dark Mode';
      case 'system':
        return 'System Theme';
      default:
        return 'Light Mode';
    }
  };
  
  return (
    <div className="relative" ref={dropdownRef}>
      <button
        id="theme-selector-button"
        aria-haspopup="true"
        aria-expanded={isOpen}
        aria-label={`Theme Settings: Currently ${getThemeName(theme)}`}
        onClick={() => setIsOpen(!isOpen)}
        className="p-2 rounded-md text-gray-900 hover:text-gray-900 hover:bg-gray-100 dark:text-white dark:hover:text-white dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary"
      >
        <span className="sr-only">Theme Settings: Currently {getThemeName(theme)}</span>
        <ThemeIcon />
      </button>
      
      {isOpen && (
        <div 
          className="absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 z-50"
          role="menu"
          aria-orientation="vertical"
          aria-labelledby="theme-selector-button"
        >
          <div className="py-1" role="none">
            <fieldset>
              <legend className="sr-only">Choose Website Theme</legend>
              
              <div className="px-4 py-2 text-sm text-gray-700 dark:text-gray-200 font-medium border-b border-gray-200 dark:border-gray-700">
                Choose Website Theme
              </div>
              
              <div className="theme-options">
                <button
                  className={`w-full text-left px-4 py-2 text-sm flex items-center gap-2 ${
                    theme === 'light' 
                      ? 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white' 
                      : 'text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                  role="menuitem"
                  onClick={() => handleThemeChange('light')}
                  aria-pressed={theme === 'light'}
                >
                  <SunIcon size={16} />
                  <span>Light Mode</span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                    (Standard brightness and colors)
                  </span>
                </button>
                
                <button
                  className={`w-full text-left px-4 py-2 text-sm flex items-center gap-2 ${
                    theme === 'dark' 
                      ? 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white' 
                      : 'text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                  role="menuitem"
                  onClick={() => handleThemeChange('dark')}
                  aria-pressed={theme === 'dark'}
                >
                  <MoonIcon size={16} />
                  <span>Dark Mode</span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                    (Reduced brightness for low light)
                  </span>
                </button>
                
                <button
                  className={`w-full text-left px-4 py-2 text-sm flex items-center gap-2 ${
                    theme === 'high-contrast-light' 
                      ? 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white' 
                      : 'text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                  role="menuitem"
                  onClick={() => handleThemeChange('high-contrast-light')}
                  aria-pressed={theme === 'high-contrast-light'}
                >
                  <HighContrastLightIcon size={16} />
                  <span>High Contrast Light</span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                    (Maximum contrast for low vision)
                  </span>
                </button>
                
                <button
                  className={`w-full text-left px-4 py-2 text-sm flex items-center gap-2 ${
                    theme === 'high-contrast-dark' 
                      ? 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white' 
                      : 'text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                  role="menuitem"
                  onClick={() => handleThemeChange('high-contrast-dark')}
                  aria-pressed={theme === 'high-contrast-dark'}
                >
                  <HighContrastDarkIcon size={16} />
                  <span>High Contrast Dark</span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                    (White on black, enhanced visibility)
                  </span>
                </button>
                
                <button
                  className={`w-full text-left px-4 py-2 text-sm flex items-center gap-2 ${
                    theme === 'system' 
                      ? 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white' 
                      : 'text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                  role="menuitem"
                  onClick={() => handleThemeChange('system')}
                  aria-pressed={theme === 'system'}
                >
                  <ContrastIcon size={16} />
                  <span>System</span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                    (Follows device preference)
                  </span>
                </button>
              </div>
            </fieldset>
            
            <div className="px-4 py-2 text-xs text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700">
              Keyboard shortcut: Ctrl + T
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ThemeSelector;
