'use client';

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

export interface Option {
  value: string | number;
  label: string;
}

interface SimpleSelectProps {
  options?: Option[];
  value?: any;
  defaultValue?: any;
  onChange?: (value: any) => void;
  onSearchChange?: (query: string) => void;
  loading?: boolean;
  disabled?: boolean;
  isMulti?: boolean;
  placeholder?: string;
  isClearable?: boolean;
  className?: string;
  noOptionsMessage?: string;
  isCreatable?: boolean;
  wrap?: boolean;
  controlBgClass?: string;
}

export default function SimpleSelect({
  options = [],
  value,
  defaultValue,
  onChange,
  onSearchChange,
  loading = false,
  disabled = false,
  isMulti = false,
  placeholder = 'Select option...',
  isClearable = true,
  className = '',
  noOptionsMessage = 'No options found',
  isCreatable = false,
  wrap = false,
  controlBgClass = 'bg-slate-50 dark:bg-slate-950',
}: SimpleSelectProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [internalValue, setInternalValue] = useState<any>(
    isMulti ? (defaultValue || []) : (defaultValue || '')
  );
  const containerRef = useRef<HTMLDivElement>(null);

  const currentValue = value !== undefined ? value : internalValue;

  const filteredOptions = options.filter(opt =>
    opt.label.toLowerCase().includes(searchQuery.toLowerCase())
  );

  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);
  }, []);

  const handleSelect = (option: Option) => {
    let newValue;
    if (isMulti) {
      const currentArray = Array.isArray(currentValue) ? currentValue : [];
      if (currentArray.includes(option.value)) {
        newValue = currentArray.filter(v => v !== option.value);
      } else {
        newValue = [...currentArray, option.value];
      }
    } else {
      newValue = option.value;
      setIsOpen(false);
    }
    if (value === undefined) {
      setInternalValue(newValue);
    }
    if (onChange) {
      onChange(newValue);
    }
  };

  const handleCreate = () => {
    if (isCreatable && searchQuery.trim()) {
      const newOption = { value: searchQuery.trim(), label: searchQuery.trim() };
      handleSelect(newOption);
      setSearchQuery('');
    }
  };

  const handleClear = () => {
    const newValue = isMulti ? [] : '';
    if (value === undefined) {
      setInternalValue(newValue);
    }
    if (onChange) {
      onChange(newValue);
    }
  };

  const handleRemove = (val: string | number) => {
    if (isMulti) {
      const newValue = (Array.isArray(currentValue) ? currentValue : []).filter(v => v !== val);
      if (value === undefined) {
        setInternalValue(newValue);
      }
      if (onChange) {
        onChange(newValue);
      }
    }
  };

  const isValueSelected = (optValue: string | number) => {
    if (isMulti) {
      return Array.isArray(currentValue) && currentValue.includes(optValue);
    }
    return currentValue === optValue;
  };

  const getSelectedLabels = () => {
    if (isMulti) {
      const arr = Array.isArray(currentValue) ? currentValue : [];
      return arr.map(v => {
        const opt = options.find(o => o.value === v);
        return opt ? opt.label : v;
      });
    }
    const opt = options.find(o => o.value === currentValue);
    return opt ? [opt.label] : [];
  };

  const selectedLabels = getSelectedLabels();

  return (
    <div className={`min-w-0 max-w-full relative ${className || 'w-full'}`} ref={containerRef}>
      <div
        className={`flex items-center justify-between border rounded-lg ${controlBgClass} px-3 ${wrap ? 'py-1' : 'py-0.5'} text-xs transition-all duration-200 cursor-pointer min-h-[34px] ${wrap ? '' : 'h-[34px]'} w-full ${isOpen ? 'border-indigo-500 ring-2 ring-indigo-500/10' : 'border-slate-200 dark:border-slate-800 hover:border-indigo-500/40 dark:hover:border-indigo-500/40'} ${disabled ? 'opacity-60 cursor-not-allowed' : ''}`}
        onClick={() => !disabled && setIsOpen(!isOpen)}
      >
        <div className={`flex items-center gap-1 text-slate-800 dark:text-slate-200 py-0 flex-1 min-w-0 ${wrap ? 'flex-wrap' : '!flex-nowrap !overflow-x-auto'}`}>
          {selectedLabels.length > 0 ? (
            isMulti ? (
              selectedLabels.map((label, idx) => {
                const arr = Array.isArray(currentValue) ? currentValue : [];
                return (
                  <span key={idx} className="bg-indigo-50/70 dark:bg-indigo-950/30 border border-indigo-100/60 dark:border-indigo-900/30 rounded-md flex items-center px-1.5 py-0.5 text-xs text-indigo-700 dark:text-indigo-400 whitespace-nowrap overflow-hidden text-ellipsis max-w-full shrink-0">
                    <span className="mr-1 overflow-hidden text-ellipsis text-[11px] font-normal leading-none">{label}</span>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        handleRemove(arr[idx]);
                      }}
                      className="text-indigo-400 hover:text-rose-600 dark:hover:text-rose-400 cursor-pointer p-0.5 rounded hover:bg-rose-50 dark:hover:bg-rose-950/30 shrink-0 transition-colors duration-150"
                    >
                      ×
                    </button>
                  </span>
                );
              })
            ) : (
              <span className="text-slate-800 dark:text-white text-xs whitespace-nowrap overflow-hidden text-ellipsis w-full block">{selectedLabels[0]}</span>
            )
          ) : (
            <span className="text-slate-400 dark:text-slate-500 text-xs whitespace-nowrap overflow-hidden text-ellipsis">{placeholder}</span>
          )}
        </div>
        <div className="flex items-center gap-0.5 text-slate-400 shrink-0">
          {isClearable && selectedLabels.length > 0 && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                handleClear();
              }}
              className="text-slate-400 hover:text-rose-600 dark:hover:text-rose-400 cursor-pointer p-0.5 transition-colors"
            >
              ×
            </button>
          )}
          <span className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 cursor-pointer p-0.5 transition-colors">
            {isOpen ? '▲' : '▼'}
          </span>
        </div>
      </div>
      {isOpen && (
        <div className="absolute left-0 right-0 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg mt-1 shadow-lg z-50 overflow-hidden w-full">
          <div className="px-3 py-2 border-b border-slate-100 dark:border-slate-800">
            <input
              type="text"
              placeholder="Search..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                if (onSearchChange) {
                  onSearchChange(e.target.value);
                }
              }}
              className="w-full bg-transparent border-none text-xs text-slate-800 dark:text-white focus:outline-none"
              autoFocus
            />
          </div>
          <div className="max-h-60 overflow-y-auto custom-scrollbar p-1">
            {loading ? (
              <div className="p-4 text-center text-xs text-slate-400">Loading...</div>
            ) : filteredOptions.length > 0 ? (
              filteredOptions.map((opt) => (
                <div
                  key={opt.value}
                  onClick={() => handleSelect(opt)}
                  className={`px-3 py-2 text-xs font-normal rounded-md cursor-pointer transition-colors duration-150 whitespace-nowrap overflow-hidden text-ellipsis w-full ${isValueSelected(opt.value) ? 'bg-indigo-600 text-white font-medium' : 'text-slate-700 dark:text-slate-350 hover:bg-slate-50 dark:hover:bg-slate-800/40'}`}
                >
                  {opt.label}
                </div>
              ))
            ) : isCreatable && searchQuery.trim() ? (
              <div
                onClick={handleCreate}
                className="px-3 py-2 text-xs font-normal rounded-md cursor-pointer transition-colors duration-150 whitespace-nowrap overflow-hidden text-ellipsis w-full text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50/70 dark:hover:bg-indigo-950/30"
              >
                Create "{searchQuery.trim()}"
              </div>
            ) : (
              <div className="p-4 text-center text-xs text-slate-400">{noOptionsMessage}</div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
