'use client';

import { useState, useMemo, useEffect, useRef } from 'react';
import { ChevronDown, Search, X, Check } from 'lucide-react';

interface Option {
  value: string | number;
  label: string;
  sublabel?: string;
}

interface SmartSelectProps {
  label?: string;
  placeholder?: string;
  options: Option[];
  value?: string | number;
  onChange: (value: string | number) => void;
  required?: boolean;
  disabled?: boolean;
  error?: string;
  helperText?: string;
  searchable?: boolean;
  pageSize?: number;
}

export function SmartSelect({
  label,
  placeholder = '-- Select --',
  options,
  value,
  onChange,
  required,
  disabled,
  error,
  helperText,
  searchable = true,
  pageSize = 20,
}: SmartSelectProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [visibleCount, setVisibleCount] = useState(pageSize);
  const listRef = useRef<HTMLDivElement>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);

  // Find selected option
  const selectedOption = useMemo(() => {
    return options.find(opt => String(opt.value) === String(value));
  }, [options, value]);

  // Filter options based on search
  const filteredOptions = useMemo(() => {
    if (!search.trim()) return options;
    const term = search.toLowerCase().trim();
    return options.filter(opt => 
      opt.label.toLowerCase().includes(term) ||
      (opt.sublabel && opt.sublabel.toLowerCase().includes(term))
    );
  }, [options, search]);

  // Paginated options
  const visibleOptions = useMemo(() => {
    return filteredOptions.slice(0, visibleCount);
  }, [filteredOptions, visibleCount]);

  const hasMore = visibleCount < filteredOptions.length;

  // Reset visible count when search changes
  useEffect(() => {
    setVisibleCount(pageSize);
  }, [search, pageSize]);

  // Focus search input when modal opens
  useEffect(() => {
    if (isOpen && searchable && searchInputRef.current) {
      setTimeout(() => searchInputRef.current?.focus(), 100);
    }
  }, [isOpen, searchable]);

  // Handle scroll to load more
  const handleScroll = () => {
    if (!listRef.current || !hasMore) return;
    const { scrollTop, scrollHeight, clientHeight } = listRef.current;
    if (scrollHeight - scrollTop - clientHeight < 100) {
      setVisibleCount(prev => prev + pageSize);
    }
  };

  // Close on escape
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        setIsOpen(false);
      }
    };
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  const handleSelect = (optionValue: string | number) => {
    onChange(optionValue);
    setIsOpen(false);
    setSearch('');
  };

  const handleOpen = () => {
    if (!disabled) {
      setIsOpen(true);
      setVisibleCount(pageSize);
    }
  };

  return (
    <div className="w-full">
      {label && (
        <label className="mb-1.5 block text-sm font-semibold text-slate-700">
          {label}
          {required && <span className="ml-1 text-red-500">*</span>}
        </label>
      )}

      {/* Trigger Button */}
      <button
        type="button"
        onClick={handleOpen}
        disabled={disabled}
        className={`
          flex w-full items-center justify-between rounded-xl border-2 px-4 py-3.5 text-left
          transition-all duration-200 focus:outline-none focus:ring-2
          ${error 
            ? 'border-red-300 bg-red-50 focus:border-red-500 focus:ring-red-200' 
            : 'border-slate-200 bg-slate-50 focus:border-emerald-500 focus:ring-emerald-500/20'
          }
          ${disabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer active:scale-[0.99]'}
        `}
      >
        <span className={selectedOption ? 'text-slate-900 font-medium' : 'text-slate-400'}>
          {selectedOption ? selectedOption.label : placeholder}
        </span>
        <ChevronDown className={`h-5 w-5 text-slate-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {error && <p className="mt-1.5 text-sm font-medium text-red-600">{error}</p>}
      {helperText && !error && <p className="mt-1.5 text-sm text-slate-500">{helperText}</p>}

      {/* Modal Overlay */}
      {isOpen && (
        <div className="fixed inset-0 z-[100] flex items-end justify-center">
          {/* Backdrop */}
          <div 
            className="absolute inset-0 bg-black/50 backdrop-blur-sm"
            onClick={() => {
              setIsOpen(false);
              setSearch('');
            }}
          />

          {/* Bottom Sheet - positioned above bottom navigation */}
          <div className="relative z-10 mb-[72px] w-full max-w-lg animate-slide-up rounded-3xl bg-white shadow-2xl mx-3">
            {/* Header */}
            <div className="flex items-center justify-between border-b border-slate-100 px-4 py-4 rounded-t-3xl">
              <h3 className="text-lg font-bold text-slate-900">
                {label || 'Select Option'}
              </h3>
              <button
                type="button"
                aria-label="Close"
                onClick={() => {
                  setIsOpen(false);
                  setSearch('');
                }}
                className="flex h-9 w-9 items-center justify-center rounded-full bg-slate-100 text-slate-500 transition-colors hover:bg-slate-200 active:scale-95"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Search Input */}
            {searchable && options.length > 5 && (
              <div className="border-b border-slate-100 px-4 py-3">
                <div className="flex items-center gap-2 rounded-xl bg-slate-100 px-3 py-2.5">
                  <Search className="h-5 w-5 text-slate-400" />
                  <input
                    ref={searchInputRef}
                    type="text"
                    placeholder="Search..."
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="flex-1 bg-transparent text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none"
                  />
                  {search && (
                    <button
                      type="button"
                      aria-label="Clear search"
                      onClick={() => setSearch('')}
                      className="text-slate-400 hover:text-slate-600"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  )}
                </div>
                <p className="mt-2 text-xs text-slate-500">
                  {filteredOptions.length} of {options.length} options
                </p>
              </div>
            )}

            {/* Options List */}
            <div
              ref={listRef}
              onScroll={handleScroll}
              className="max-h-[50vh] overflow-y-auto overscroll-contain"
            >
              {visibleOptions.length === 0 ? (
                <div className="px-4 py-8 text-center">
                  <p className="text-sm text-slate-500">No options found</p>
                  {search && (
                    <button
                      type="button"
                      onClick={() => setSearch('')}
                      className="mt-2 text-sm font-medium text-emerald-600"
                    >
                      Clear search
                    </button>
                  )}
                </div>
              ) : (
                <div className="py-2">
                  {visibleOptions.map((option) => {
                    const isSelected = String(option.value) === String(value);
                    return (
                      <button
                        key={option.value}
                        type="button"
                        onClick={() => handleSelect(option.value)}
                        className={`flex w-full items-center gap-3 px-4 py-3.5 text-left transition-colors active:bg-slate-100 ${
                          isSelected ? 'bg-emerald-50' : 'hover:bg-slate-50'
                        }`}
                      >
                        <div className="flex-1 min-w-0">
                          <p className={`truncate text-sm ${isSelected ? 'font-semibold text-emerald-700' : 'text-slate-900'}`}>
                            {option.label}
                          </p>
                          {option.sublabel && (
                            <p className="mt-0.5 truncate text-xs text-slate-500">
                              {option.sublabel}
                            </p>
                          )}
                        </div>
                        {isSelected && (
                          <div className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-emerald-500">
                            <Check className="h-4 w-4 text-white" />
                          </div>
                        )}
                      </button>
                    );
                  })}

                  {/* Load More */}
                  {hasMore && (
                    <div className="px-4 py-3 text-center">
                      <button
                        type="button"
                        onClick={() => setVisibleCount(prev => prev + pageSize)}
                        className="text-sm font-medium text-emerald-600"
                      >
                        Load more ({filteredOptions.length - visibleCount} remaining)
                      </button>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Bottom padding for rounded corners */}
            <div className="h-3 rounded-b-3xl bg-white" />
          </div>
        </div>
      )}

      {/* Animation styles */}
      <style jsx global>{`
        @keyframes slide-up {
          from {
            transform: translateY(100%);
            opacity: 0;
          }
          to {
            transform: translateY(0);
            opacity: 1;
          }
        }
        .animate-slide-up {
          animation: slide-up 0.25s ease-out;
        }
      `}</style>
    </div>
  );
}
