'use client';

import { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';

const Pill = ({ option, onRemove }) => (
  <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border bg-neutral-100 dark:bg-neutral-700 border-neutral-200 dark:border-neutral-600 text-neutral-700 dark:text-neutral-300">
    {option.label}
    <button
      type="button"
      onClick={(e) => { e.stopPropagation(); onRemove(); }}
      className="ml-0.5 hover:opacity-70 transition-opacity leading-none"
      aria-label={`Retirer ${option.label}`}
    >
      ×
    </button>
  </span>
);

const TagInput = ({
  options = [],
  value = [],
  onChange,
  label,
  description,
  placeholder = 'Ajouter...',
  error,
  renderTag,
}) => {
  const [inputValue, setInputValue] = useState('');
  const [isOpen, setIsOpen] = useState(false);
  const [dropdownStyle, setDropdownStyle] = useState({});
  const containerRef = useRef(null);
  const inputRef = useRef(null);

  const selectedOptions = value.map(v => options.find(o => o.value === v)).filter(Boolean);
  const filtered = options.filter(o =>
    !value.includes(o.value) &&
    o.label.toLowerCase().includes(inputValue.toLowerCase())
  );

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

  useEffect(() => {
    if (!isOpen || !containerRef.current) return;
    const updatePosition = () => {
      const rect = containerRef.current?.getBoundingClientRect();
      if (rect) {
        setDropdownStyle({ top: rect.bottom + 6, left: rect.left, width: rect.width });
      }
    };
    updatePosition();
    window.addEventListener('scroll', updatePosition, true);
    window.addEventListener('resize', updatePosition);
    return () => {
      window.removeEventListener('scroll', updatePosition, true);
      window.removeEventListener('resize', updatePosition);
    };
  }, [isOpen]);

  const selectOption = (option) => {
    onChange([...value, option.value]);
    setInputValue('');
    inputRef.current?.focus();
  };

  const removeOption = (val) => {
    onChange(value.filter(v => v !== val));
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Backspace' && inputValue === '' && value.length > 0) {
      onChange(value.slice(0, -1));
    }
    if (e.key === 'Escape') {
      setIsOpen(false);
    }
  };

  return (
    <div className="space-y-2" ref={containerRef}>
      {label && (
        <label className="block text-xs font-medium text-neutral-700 dark:text-white">
          {label}
        </label>
      )}

      <div
        className={`relative w-full flex flex-wrap items-center gap-1.5 px-[10px] py-[7px] rounded-lg border text-[13px] bg-white dark:bg-neutral-900/60 cursor-text transition-all duration-[120ms] ease-out ${
          isOpen
            ? 'border-neutral-500 ring-1 ring-neutral-500/20 dark:border-neutral-600 dark:ring-neutral-600/20'
            : error
            ? 'border-red-500/50 dark:border-red-500/50'
            : 'border-neutral-300 dark:border-neutral-700/50 hover:border-neutral-400 dark:hover:border-neutral-600'
        }`}
        onClick={() => { inputRef.current?.focus(); setIsOpen(true); }}
      >
        {selectedOptions.map(opt => (
          renderTag
            ? renderTag(opt, () => removeOption(opt.value))
            : <Pill key={opt.value} option={opt} onRemove={() => removeOption(opt.value)} />
        ))}

        <input
          ref={inputRef}
          type="text"
          value={inputValue}
          onChange={(e) => { setInputValue(e.target.value); setIsOpen(true); }}
          onFocus={() => setIsOpen(true)}
          onKeyDown={handleKeyDown}
          placeholder={value.length === 0 ? placeholder : ''}
          className="flex-1 min-w-[80px] bg-transparent outline-none text-neutral-900 dark:text-white placeholder-neutral-400 dark:placeholder-neutral-500 text-sm"
        />

        {isOpen && filtered.length > 0 && createPortal(
          <div className="z-[9999] bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-xl shadow-lg overflow-hidden max-h-56 overflow-y-auto" style={{ position: 'fixed', ...dropdownStyle }}>
            {filtered.map(option => (
              <button
                key={option.value}
                type="button"
                onMouseDown={(e) => { e.preventDefault(); selectOption(option); }}
                className="w-full flex items-center gap-2.5 px-3 py-2 text-sm text-left hover:bg-neutral-50 dark:hover:bg-neutral-700/50 transition-colors"
              >
                {option.color && (
                  <span
                    className="inline-block w-3 h-3 rounded-full flex-shrink-0"
                    style={{ backgroundColor: option.color }}
                  />
                )}
                <span className="text-neutral-900 dark:text-white font-medium">{option.label}</span>
                {option.description && (
                  <span className="text-xs text-neutral-400 ml-auto">{option.description}</span>
                )}
              </button>
            ))}
          </div>,
          document.body
        )}

        {isOpen && filtered.length === 0 && inputValue && createPortal(
          <div className="z-[9999] bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-xl shadow-lg overflow-hidden" style={{ position: 'fixed', ...dropdownStyle }}>
            <p className="px-3 py-2.5 text-sm text-neutral-400 dark:text-neutral-500">Aucun résultat</p>
          </div>,
          document.body
        )}
      </div>

      {description && !error && (
        <p className="text-xs text-neutral-500 dark:text-neutral-400">{description}</p>
      )}
      {error && (
        <p className="text-xs text-red-500 dark:text-red-400">{error}</p>
      )}
    </div>
  );
};

export default TagInput;
