import { useEffect, useId, useRef, useState } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';
import { FONT_FAMILY_SANS, INPUT_ERROR_TEXT_STYLE, COLOR_INPUT_ERROR } from '../../../designTokens';
import {
  PRIMARY_DROPDOWN_SELECT_ACTIVE_COLOR,
  PRIMARY_DROPDOWN_SELECT_HOVER_CSS,
  PRIMARY_DROPDOWN_SELECT_ITEM_STYLE,
  PRIMARY_DROPDOWN_SELECT_MENU_STYLE,
  PRIMARY_DROPDOWN_SELECT_TRIGGER_STYLE,
} from './primaryDropdownSelectStyles';

/**
 * Select custom con menú desplegable (hover gris, ítem seleccionado morado #6D3856).
 * Misma API de label/error/required que `PrimarySelect`; `onChange` recibe evento con `target.value`.
 */
export const PrimaryDropdownSelect = ({
  label = '',
  labelStyle,
  labelClassName = '',
  options = [],
  value,
  onChange,
  placeholder = '',
  disabled = false,
  error = '',
  required = false,
  showRequiredIndicator = true,
  activeColor = PRIMARY_DROPDOWN_SELECT_ACTIVE_COLOR,
  className = '',
  style = {},
  id,
  name,
  ...props
}) => {
  const autoId = useId();
  const fieldId = id ?? `primary-dropdown-select-${autoId.replace(/:/g, '')}`;
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef(null);
  const selectedOption = options.find((option) => String(option.value) === String(value ?? ''));
  const displayLabel = selectedOption?.label ?? (placeholder || '');

  useEffect(() => {
    if (!isOpen) return undefined;
    const handleClickOutside = (event) => {
      if (containerRef.current && !containerRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isOpen]);

  const emitChange = (nextValue) => {
    onChange?.({
      target: { value: nextValue, name: name ?? fieldId },
      currentTarget: { value: nextValue, name: name ?? fieldId },
    });
  };

  const triggerBorderColor = error ? COLOR_INPUT_ERROR : '#38656D';
  const triggerBorderWidth = error ? '2px' : '1px';

  return (
    <div ref={containerRef} className="anima-primary-dropdown-select" style={{ width: '100%', position: 'relative' }}>
      <style>{PRIMARY_DROPDOWN_SELECT_HOVER_CSS}</style>
      {label ? (
        <label
          htmlFor={fieldId}
          className={labelClassName}
          style={{
            display: 'block',
            marginBottom: '8px',
            fontFamily: FONT_FAMILY_SANS,
            fontWeight: 500,
            fontSize: '14px',
            lineHeight: '21px',
            letterSpacing: '0.01em',
            color: 'var(--color-main-800)',
            ...(labelStyle || {}),
          }}
        >
          {label}
          {required && showRequiredIndicator ? (
            <span style={{ color: '#000000', marginLeft: '4px' }}>*</span>
          ) : null}
        </label>
      ) : null}

      <div className="anima-primary-dropdown-select__control" style={{ position: 'relative', width: '100%' }}>
        <button
          type="button"
          id={fieldId}
          name={name}
          disabled={disabled}
          aria-haspopup="listbox"
          aria-expanded={isOpen}
          aria-invalid={!!error}
          className={className}
          onClick={() => !disabled && setIsOpen((prev) => !prev)}
          style={{
            ...PRIMARY_DROPDOWN_SELECT_TRIGGER_STYLE,
            borderWidth: triggerBorderWidth,
            borderColor: triggerBorderColor,
            color: selectedOption ? PRIMARY_DROPDOWN_SELECT_TRIGGER_STYLE.color : '#777777',
            fontStyle: selectedOption ? 'normal' : 'italic',
            opacity: disabled ? 0.6 : 1,
            cursor: disabled ? 'not-allowed' : 'pointer',
            ...(disabled ? { backgroundColor: '#F3F4F6' } : {}),
            ...style,
          }}
          {...props}
        >
          <span
            style={{
              display: 'block',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              textAlign: 'left',
              paddingRight: 8,
            }}
          >
            {displayLabel}
          </span>
        </button>

        <Icon
          name="ChevronDownIcon"
          variant="24-outline"
          size={18}
          style={{
            position: 'absolute',
            right: '12px',
            top: '50%',
            transform: 'translateY(-50%)',
            pointerEvents: 'none',
            color: '#38656D',
          }}
          aria-hidden
        />

        {isOpen && !disabled ? (
          <div
            role="listbox"
            className="anima-primary-dropdown-select__menu"
            style={PRIMARY_DROPDOWN_SELECT_MENU_STYLE}
          >
            {options.map((option) => {
              const isSelected = String(option.value) === String(value ?? '');
              return (
                <button
                  key={String(option.value)}
                  type="button"
                  role="option"
                  aria-selected={isSelected}
                  className="anima-primary-dropdown-select__item"
                  onClick={() => {
                    emitChange(option.value);
                    setIsOpen(false);
                  }}
                  style={{
                    ...PRIMARY_DROPDOWN_SELECT_ITEM_STYLE,
                    background: isSelected ? activeColor : '#FFFFFF',
                    color: isSelected ? '#FFFFFF' : '#29474C',
                  }}
                >
                  {option.label}
                </button>
              );
            })}
          </div>
        ) : null}
      </div>

      {error ? (
        <p
          id={`${fieldId}-error`}
          style={{
            margin: '4px 0 0',
            ...INPUT_ERROR_TEXT_STYLE,
          }}
        >
          {error}
        </p>
      ) : null}
    </div>
  );
};

export default PrimaryDropdownSelect;
