'use client';

import React, { useState, useEffect, useRef } from 'react';
import { Search, ChevronDown, Loader2 } from 'lucide-react';

interface Option {
  id: number;
  name: string;
}

interface SearchableSelectProps {
  options: Option[];
  value: number | '';
  onChange: (val: number | '') => void;
  placeholder: string;
  disabled?: boolean;
  required?: boolean;
  loading?: boolean;
  textSizeClass?: string;
}

export function SearchableSelect({
  options,
  value,
  onChange,
  placeholder,
  disabled = false,
  required = false,
  loading = false,
  textSizeClass = 'text-[15px]',
}: SearchableSelectProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const containerRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Reset search term when dropdown is closed/opened
  useEffect(() => {
    if (!isOpen) {
      setSearchTerm('');
    }
  }, [isOpen]);

  const selectedOption = options.find((opt) => opt.id === value);

  const filteredOptions = options.filter((opt) =>
    opt.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleSelect = (optId: number | '') => {
    onChange(optId);
    setIsOpen(false);
  };

  return (
    <div ref={containerRef} className="relative w-full select-none font-open-sans">
      {/* Trigger Box */}
      <div
        onClick={() => !disabled && !loading && setIsOpen(!isOpen)}
        className={`w-full flex items-center justify-between ${textSizeClass} font-medium font-open-sans px-4 py-3 bg-white border border-slate-200 rounded-xl cursor-pointer shadow-sm transition-all ${
          disabled || loading ? 'opacity-50 cursor-not-allowed bg-slate-50' : 'hover:border-slate-300'
        } ${isOpen ? 'border-secondary ring-1 ring-secondary' : ''}`}
      >
        <span className={selectedOption ? 'text-slate-800' : 'text-slate-400'}>
          {loading ? 'Loading...' : (selectedOption ? selectedOption.name : placeholder)}
        </span>
        {loading ? (
          <Loader2 className="h-4 w-4 text-slate-400 animate-spin" />
        ) : (
          <ChevronDown className={`h-4 w-4 text-slate-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
        )}
      </div>

      {/* Required native input for HTML5 form validation */}
      {required && (
        <input
          type="text"
          value={value || ''}
          onChange={() => {}}
          tabIndex={-1}
          required
          className="absolute inset-0 w-full h-full opacity-0 pointer-events-none"
        />
      )}

      {/* Dropdown Menu */}
      {isOpen && (
        <div className="absolute z-50 mt-1.5 w-full bg-white border border-slate-200 rounded-xl shadow-lg overflow-hidden flex flex-col max-h-[300px]">
          {/* Search Box */}
          <div className="p-2 border-b border-slate-100 flex items-center bg-white sticky top-0 z-10">
            <input
              type="text"
              placeholder="Search..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className={`w-full ${textSizeClass} font-medium font-open-sans px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:border-secondary focus:bg-white text-slate-800 placeholder-slate-400 pr-8`}
              autoFocus
            />
            <Search className="absolute right-4 h-4 w-4 text-slate-400 pointer-events-none" />
          </div>

          {/* Options List */}
          <div className="overflow-y-auto flex-1 max-h-[220px] divide-y divide-slate-50 no-scrollbar">
            {/* Default Option if value exists to deselect */}
            <div
              onClick={() => handleSelect('')}
              className={`px-4 py-2.5 ${textSizeClass} font-medium font-open-sans text-slate-400 hover:bg-slate-50 cursor-pointer transition-colors ${
                value === '' ? 'bg-slate-50 text-secondary font-semibold' : ''
              }`}
            >
              {placeholder}
            </div>

            {filteredOptions.length > 0 ? (
              filteredOptions.map((opt) => (
                <div
                  key={opt.id}
                  onClick={() => handleSelect(opt.id)}
                  className={`px-4 py-2.5 ${textSizeClass} font-medium font-open-sans text-slate-700 hover:bg-slate-50 cursor-pointer transition-colors ${
                    value === opt.id ? 'bg-primary/10 text-secondary font-semibold' : ''
                  }`}
                >
                  {opt.name}
                </div>
              ))
            ) : (
              <div className={`px-4 py-3 ${textSizeClass} font-medium font-open-sans text-slate-400 text-center italic`}>
                No matches found
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
