import React, { useState, useRef, useEffect } from 'react';
import { Plus, PenLine, X } from 'lucide-react';
import { cn } from '@/lib/utils';

interface ManualLineInputProps {
   value: string;
   onChange: (value: string) => void;
   onCreateArticle: (designation: string) => void;
   onAcceptFreeText: () => void;
   placeholder?: string;
   className?: string;
}

export const ManualLineInput: React.FC<ManualLineInputProps> = ({
   value,
   onChange,
   onCreateArticle,
   onAcceptFreeText,
   placeholder = "Saisir une désignation...",
   className
}) => {
   const [isOpen, setIsOpen] = useState(false);
   const [isFocused, setIsFocused] = useState(false);
   const inputRef = useRef<HTMLInputElement>(null);
   const containerRef = useRef<HTMLDivElement>(null);

   // Fermer le menu si clic à l'extérieur
   useEffect(() => {
      const handleClickOutside = (event: MouseEvent) => {
         if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
            setIsOpen(false);
         }
      };

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

   // Ouvrir le menu quand on tape
   useEffect(() => {
      if (value && isFocused) {
         setIsOpen(true);
      }
   }, [value, isFocused]);

   const handleFocus = () => {
      setIsFocused(true);
      if (value) setIsOpen(true);
   };

   const handleBlur = () => {
      setIsFocused(false);
      // Délai pour permettre le clic sur les options
      setTimeout(() => {
         if (!containerRef.current?.contains(document.activeElement)) {
            setIsOpen(false);
         }
      }, 150);
   };

   const handleCreateArticle = () => {
      if (value.trim()) {
         onCreateArticle(value.trim());
         setIsOpen(false);
      }
   };

   const handleAcceptFreeText = () => {
      onAcceptFreeText();
      setIsOpen(false);
   };

   const handleClear = () => {
      onChange('');
      inputRef.current?.focus();
   };

   return (
      <div ref={containerRef} className="relative">
         {/* Input */}
         <div className="relative">
            <input
               ref={inputRef}
               type="text"
               value={value}
               onChange={(e) => onChange(e.target.value)}
               onFocus={handleFocus}
               onBlur={handleBlur}
               placeholder={placeholder}
               className={cn(
                  "w-full px-3 py-2 pr-8 rounded-lg border text-sm transition-all",
                  "focus:outline-none focus:ring-2",
                  isOpen && value
                     ? "border-[#007E45] ring-2 ring-[#007E45]/20 bg-white"
                     : "border-gray-200 bg-white focus:border-[#007E45] focus:ring-[#007E45]/20",
                  className
               )}
            />
            
            {/* Clear button */}
            {value && (
               <button
                  type="button"
                  onClick={handleClear}
                  className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"
               >
                  <X className="w-4 h-4" />
               </button>
            )}
         </div>

         {/* Dropdown Menu */}
         {isOpen && value && (
            <div className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-xl shadow-lg overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
               {/* Option: Créer l'article */}
               <button
                  type="button"
                  onClick={handleCreateArticle}
                  className="w-full px-4 py-3 flex items-center gap-3 hover:bg-green-50 transition-colors text-left group"
               >
                  <div className="p-1.5 bg-[#007E45] rounded-lg text-white group-hover:scale-110 transition-transform">
                     <Plus className="w-4 h-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                     <p className="text-sm font-medium text-gray-900">
                        Créer l'article "<span className="text-[#007E45]">{value}</span>"
                     </p>
                     <p className="text-xs text-gray-500">Ajouter au catalogue</p>
                  </div>
               </button>

               {/* Séparateur */}
               <div className="border-t border-gray-100" />

               {/* Option: Texte libre */}
               <button
                  type="button"
                  onClick={handleAcceptFreeText}
                  className="w-full px-4 py-3 flex items-center gap-3 hover:bg-amber-50 transition-colors text-left group"
               >
                  <div className="p-1.5 bg-amber-100 rounded-lg text-amber-600 group-hover:scale-110 transition-transform">
                     <PenLine className="w-4 h-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                     <p className="text-sm font-medium text-gray-900">
                        Texte libre accepté
                     </p>
                     <p className="text-xs text-gray-500">Utiliser sans créer d'article</p>
                  </div>
               </button>
            </div>
         )}
      </div>
   );
};

export default ManualLineInput;