'use client';

import { useRef, useEffect } from 'react';
import { Search, X, Loader2, ChevronDown } from 'lucide-react';

interface AutocompleteInputProps<T> {
  value: string;
  onChange: (value: string) => void;
  options: T[];
  onSelect: (option: T) => void;
  onClear: () => void;
  getOptionLabel: (option: T) => string;
  getOptionSublabel?: (option: T) => string | null;
  placeholder: string;
  isLoading?: boolean;
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  selectedValue?: T | null;
  icon?: React.ReactNode;
  className?: string;
  emptyMessage?: string;
  minChars?: number;
}

export function AutocompleteInput<T>({
  value,
  onChange,
  options,
  onSelect,
  onClear,
  getOptionLabel,
  getOptionSublabel,
  placeholder,
  isLoading = false,
  isOpen,
  onOpenChange,
  selectedValue,
  icon,
  className = '',
  emptyMessage = 'No results found',
  minChars = 2,
}: AutocompleteInputProps<T>) {
  const containerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Handle click outside to close dropdown
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        onOpenChange(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [onOpenChange]);

  const showDropdown = isOpen && (minChars === 0 || value.length >= minChars || options.length > 0);
  const hasSelection = !!selectedValue;

  return (
    <div ref={containerRef} className={`relative ${className}`}>
      <div className="relative">
        {/* Icon */}
        <div className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400">
          {icon || <Search className="h-4 w-4" />}
        </div>

        {/* Input */}
        <input
          ref={inputRef}
          type="text"
          value={value}
          onChange={(e) => {
            onChange(e.target.value);
            if (!isOpen) onOpenChange(true);
          }}
          onFocus={() => onOpenChange(true)}
          placeholder={placeholder}
          className={`w-full rounded-xl border py-3 pl-10 pr-10 text-sm transition-all focus:outline-none focus:ring-2 ${
            hasSelection
              ? 'border-emerald-300 bg-emerald-50 text-emerald-800 focus:border-emerald-500 focus:ring-emerald-500/20'
              : 'border-slate-200 bg-white text-slate-900 placeholder-slate-400 focus:border-emerald-500 focus:ring-emerald-500/20'
          }`}
        />

        {/* Right side icons */}
        <div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-1">
          {isLoading && <Loader2 className="h-4 w-4 animate-spin text-slate-400" />}
          {hasSelection && !isLoading && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                onClear();
                inputRef.current?.focus();
              }}
              className="p-0.5 rounded-full hover:bg-slate-100 text-slate-400 hover:text-slate-600"
              title="Clear selection"
              aria-label="Clear selection"
            >
              <X className="h-4 w-4" />
            </button>
          )}
          {!hasSelection && !isLoading && (
            <ChevronDown className={`h-4 w-4 text-slate-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
          )}
        </div>
      </div>

      {/* Dropdown */}
      {showDropdown && (
        <div className="absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-xl border border-slate-200 bg-white shadow-lg">
          {options.length === 0 && !isLoading ? (
            <div className="px-4 py-3 text-sm text-slate-500 text-center">
              {minChars > 0 && value.length < minChars ? `Type at least ${minChars} characters...` : emptyMessage}
            </div>
          ) : (
            options.map((option, index) => {
              const label = getOptionLabel(option);
              const sublabel = getOptionSublabel?.(option);
              return (
                <button
                  key={index}
                  onClick={() => onSelect(option)}
                  className="w-full px-4 py-3 text-left hover:bg-slate-50 transition-colors border-b border-slate-100 last:border-b-0"
                >
                  <div className="font-medium text-slate-900 text-sm truncate">{label}</div>
                  {sublabel && (
                    <div className="text-xs text-slate-500 mt-0.5 truncate">{sublabel}</div>
                  )}
                </button>
              );
            })
          )}
        </div>
      )}
    </div>
  );
}

interface FilterChipProps {
  label: string;
  value: string;
  onClear: () => void;
  color?: 'emerald' | 'blue' | 'amber' | 'purple';
}

export function FilterChip({ label, value, onClear, color = 'emerald' }: FilterChipProps) {
  const colorClasses = {
    emerald: 'bg-emerald-50 text-emerald-700 border-emerald-200',
    blue: 'bg-blue-50 text-blue-700 border-blue-200',
    amber: 'bg-amber-50 text-amber-700 border-amber-200',
    purple: 'bg-purple-50 text-purple-700 border-purple-200',
  };

  return (
    <div className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full border text-xs font-medium ${colorClasses[color]}`}>
      <span className="text-slate-500">{label}:</span>
      <span className="truncate max-w-[150px]">{value}</span>
      <button
        onClick={onClear}
        className="p-0.5 rounded-full hover:bg-white/50 transition-colors"
        title={`Remove ${label} filter`}
        aria-label={`Remove ${label} filter`}
      >
        <X className="h-3 w-3" />
      </button>
    </div>
  );
}
