'use client';

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

const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) }
    : null;
};

const Pill = ({ option, onRemove }) => {
  const rgb = option.color ? hexToRgb(option.color) : null;
  const pillStyle = rgb
    ? { backgroundColor: `rgba(${rgb.r},${rgb.g},${rgb.b},0.15)`, borderColor: `rgba(${rgb.r},${rgb.g},${rgb.b},0.4)`, color: option.color }
    : {};
  const fallbackClass = !rgb
    ? 'bg-neutral-100 dark:bg-neutral-700 border-neutral-200 dark:border-neutral-600 text-neutral-700 dark:text-neutral-300'
    : '';

  return (
    <span
      className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${fallbackClass}`}
      style={pillStyle}
    >
      {option.color && (
        <span
          className="inline-block w-2 h-2 rounded-full flex-shrink-0"
          style={{ backgroundColor: option.color }}
        />
      )}
      {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,
}) => {
  const [inputValue, setInputValue] = useState('');
  const [isOpen, setIsOpen] = useState(false);
  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);
  }, []);

  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="flex flex-col gap-1.5" ref={containerRef}>
      {label && (
        <label className="text-xs font-medium text-neutral-700 dark:text-neutral-300">
          {label}
        </label>
      )}

      <div
        className={`relative min-h-[42px] w-full flex flex-wrap items-center gap-1.5 px-3 py-2 rounded-xl border text-sm bg-white dark:bg-neutral-900 cursor-text transition-shadow ${
          isOpen
            ? 'border-blue-500 ring-2 ring-blue-500/20'
            : error
            ? 'border-red-400 dark:border-red-500'
            : 'border-neutral-200 dark:border-neutral-700 hover:border-neutral-300 dark:hover:border-neutral-600'
        }`}
        onClick={() => { inputRef.current?.focus(); setIsOpen(true); }}
      >
        {selectedOptions.map(opt => (
          <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 && (
          <div className="absolute top-full left-0 right-0 mt-1.5 z-50 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">
            {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>
        )}

        {isOpen && filtered.length === 0 && inputValue && (
          <div className="absolute top-full left-0 right-0 mt-1.5 z-50 bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-xl shadow-lg overflow-hidden">
            <p className="px-3 py-2.5 text-sm text-neutral-400 dark:text-neutral-500">Aucun résultat</p>
          </div>
        )}
      </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;
