import React, { useState, useRef, useEffect } from 'react';

export default function SelectChoice({
  type,
  name,
  label,
  required,
  placeHolder,
  choices,
  callback,
  selected,
  errorMsg,
  errorLocalMsg,
  IconItem,
  disabled = false,
  // Nouveaux paramètres
  showIcons = false, // Activer l'affichage des icônes dans les options
  customSelect = false, // Utiliser une liste personnalisée au lieu du select natif
}) {
  const isPlaceholderSelected = selected === ''; // Vérifie si le placeholder est sélectionné
  const [isOpen, setIsOpen] = useState(false);
  const [selectedLabel, setSelectedLabel] = useState('');
  const dropdownRef = useRef(null);

  // Ferme le dropdown si on clique en dehors
  useEffect(() => {
    function handleClickOutside(event) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    }

    if (customSelect) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [customSelect]);

  // Met à jour le label affiché quand selected change
  useEffect(() => {
    if (selected && choices) {
      const selectedOption = choices.find(
        (option) => option.value === selected
      );
      if (selectedOption) {
        setSelectedLabel(selectedOption.label);
      }
    } else {
      setSelectedLabel('');
    }
  }, [selected, choices]);

  // Affiche soit le select natif, soit notre version personnalisée avec icônes
  return (
    <>
      <div>
        <label
          htmlFor={name}
          className="block text-sm font-medium text-gray-700"
        >
          {label}
          {required && <span className="text-red-500 ml-1">*</span>}
        </label>

        {customSelect ? (
          // Version personnalisée avec icônes dans un dropdown
          <div ref={dropdownRef} className="relative">
            <div
              className={`mt-1 flex items-center border rounded-md cursor-pointer ${
                errorMsg || errorLocalMsg
                  ? 'border-red-500 hover:border-red-700'
                  : 'border-gray-200 hover:border-gray-400'
              } ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
              onClick={() => !disabled && setIsOpen(!isOpen)}
            >
              {IconItem && (
                <span className="inline-flex items-center px-3 text-gray-500 text-sm">
                  {<IconItem />}
                </span>
              )}
              <div className="flex-1 px-3 py-2 block w-full sm:text-sm">
                {isPlaceholderSelected ? (
                  <span className="italic text-gray-500">
                    {placeHolder?.toLowerCase()}
                  </span>
                ) : (
                  <div className="flex items-center">
                    {showIcons && selected && choices && (
                      <span className="mr-2">
                        {(() => {
                          const selectedOption = choices.find(
                            (option) => option.value === selected
                          );
                          if (selectedOption && selectedOption.icon) {
                            const IconComponent = selectedOption.icon;
                            return (
                              <IconComponent
                                size={18}
                                className="text-gray-600"
                              />
                            );
                          }
                          return null;
                        })()}
                      </span>
                    )}
                    <span className="text-gray-800">{selectedLabel}</span>
                  </div>
                )}
              </div>
              <div className="pr-2">
                <svg
                  className={`h-5 w-5 text-gray-400 transition-transform ${isOpen ? 'transform rotate-180' : ''}`}
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                  aria-hidden="true"
                >
                  <path
                    fillRule="evenodd"
                    d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                    clipRule="evenodd"
                  />
                </svg>
              </div>
            </div>

            {isOpen && (
              <div className="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md py-1 max-h-60 overflow-auto">
                <div
                  className="px-3 py-2 text-gray-500 italic cursor-pointer hover:bg-gray-100"
                  onClick={() => {
                    if (!disabled) {
                      const event = { target: { value: '' } };
                      callback(event);
                      setIsOpen(false);
                    }
                  }}
                >
                  {placeHolder?.toLowerCase()}
                </div>
                {choices.map(({ value, label, icon: Icon }) => (
                  <div
                    key={value}
                    className={`px-3 py-2 cursor-pointer hover:bg-gray-100 ${
                      value === selected
                        ? 'bg-blue-50 text-blue-700'
                        : 'text-gray-800'
                    }`}
                    onClick={() => {
                      if (!disabled) {
                        const event = { target: { value } };
                        callback(event);
                        setIsOpen(false);
                      }
                    }}
                  >
                    <div className="flex items-center">
                      {showIcons && Icon && (
                        <span className="mr-2">
                          <Icon
                            size={18}
                            className={
                              value === selected
                                ? 'text-blue-600'
                                : 'text-gray-600'
                            }
                          />
                        </span>
                      )}
                      <span>{label}</span>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* Input caché pour la compatibilité avec les formulaires */}
            <input
              type="hidden"
              name={name}
              id={name}
              value={selected || ''}
              onChange={() => {}} // Évite l'avertissement React pour input non contrôlé
            />
          </div>
        ) : (
          // Version standard avec select natif (pour la rétrocompatibilité)
          <div
            className={`mt-1 flex items-center border rounded-md ${
              errorMsg || errorLocalMsg
                ? 'border-red-500 hover:border-red-700'
                : 'border-gray-200 hover:border-gray-400'
            } ${disabled ? '' : 'focus-within:border-gray-500'}`}
          >
            {IconItem && (
              <span className="inline-flex items-center px-3 text-gray-500 text-sm">
                {<IconItem />}
              </span>
            )}
            <select
              className={`flex-1 px-3 py-2 block w-full sm:text-sm border-none focus:ring-0 outline-none rounded-md ${
                disabled ? 'bg-gray-100' : ''
              } ${isPlaceholderSelected ? 'italic text-gray-500' : 'not-italic text-gray-800'}`}
              type={type}
              id={name}
              name={name}
              value={selected}
              onChange={callback}
              disabled={disabled}
            >
              {/* Placeholder en italique */}
              <option value="" className="italic text-gray-500">
                {placeHolder?.toLowerCase()}
              </option>
              {/* Autres options sans italique */}
              {choices.map(({ value, label }) => (
                <option
                  key={value}
                  value={value}
                  className="not-italic text-gray-800"
                >
                  {label}
                </option>
              ))}
            </select>
          </div>
        )}

        {errorMsg && <p className="mt-2 text-sm text-red-600">{errorMsg}</p>}
      </div>
    </>
  );
}
