'use client';

import { useState } from 'react';
import { Check } from 'lucide-react';
import { useTheme } from '@/contexts/ThemeContext';
import { Theme, THEME_CONFIG, getThemeIcon } from '@/lib/ui-config';
import { Emoji } from '@/components/ui/Emoji';

interface ThemeDropdownProps {
  variant: 'desktop' | 'mobile';
  className?: string;
}

export function ThemeDropdown({ variant, className = '' }: ThemeDropdownProps) {
  const { theme, setTheme } = useTheme();
  const [themeDropdownOpen, setThemeDropdownOpen] = useState(false);

  // Liste des thèmes disponibles avec leurs labels et icônes
  const themes: { value: Theme; label: string; icon: string }[] =
    THEME_CONFIG.allThemes.map((themeValue) => {
      return {
        value: themeValue,
        label:
          themeValue.charAt(0).toUpperCase() +
          themeValue.slice(1).replace('_', ' '),
        icon: getThemeIcon(themeValue),
      };
    });

  const buttonSize = variant === 'mobile' ? 'p-2' : 'p-1';

  return (
    <div className={`relative ${className}`}>
      <button
        onClick={() => setThemeDropdownOpen(!themeDropdownOpen)}
        className={`text-[var(--muted-foreground)] hover:text-[var(--primary)] transition-colors ${buttonSize} rounded-md hover:bg-[var(--card-hover)]`}
        title="Select theme"
      >
        <Emoji emoji={themes.find((t) => t.value === theme)?.icon || '🎨'} />
      </button>

      {themeDropdownOpen && (
        <>
          {/* Backdrop */}
          <div
            className="fixed inset-0 z-[200]"
            onClick={() => setThemeDropdownOpen(false)}
          />
          {/* Dropdown */}
          <div className="absolute right-0 top-full mt-2 w-48 bg-[var(--card)] border border-[var(--border)] rounded-lg shadow-lg z-[201] overflow-hidden">
            <div className="py-2">
              {themes.map((themeOption) => (
                <button
                  key={themeOption.value}
                  onClick={() => {
                    setTheme(themeOption.value);
                    setThemeDropdownOpen(false);
                  }}
                  className={`w-full text-left px-4 py-2 text-sm transition-colors flex items-center gap-3 ${
                    theme === themeOption.value
                      ? 'text-[var(--primary)] bg-[var(--primary)]/10'
                      : 'text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:bg-[var(--card-hover)]'
                  }`}
                >
                  <Emoji emoji={themeOption.icon} />
                  <span className="font-mono">{themeOption.label}</span>
                  {theme === themeOption.value && (
                    <Check className="w-4 h-4 ml-auto" />
                  )}
                </button>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
