'use client';

import { useState } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
import SearchBox from './SearchBox';

interface ActiveSearchboxProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'results'> {
  onSearch?: (value: string) => void;
  results?: Array<{ id: string; title: string }>;
  isLoading?: boolean;
  onResultSelect?: (result: { id: string; title: string }) => void;
}

export function ActiveSearchbox({
  className,
  onSearch,
  results = [],
  isLoading = false,
  onResultSelect,
  ...props
}: ActiveSearchboxProps) {
  const [isOpen, setIsOpen] = useState(false);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    onSearch?.(value);
    setIsOpen(true);
  };

  return (
    <div className="map-search-container">
      <SearchBox 
        className={className}
        onFocus={() => setIsOpen(true)} 
        onChange={handleInputChange} 
        {...props}
        />
      {isOpen && (isLoading || results.length > 0) && (
        <div className="map-search-results">
          {isLoading ? (
            <>
              <div className="p-4">
                <Skeleton className="h-4 w-3/4 mb-2" />
                <Skeleton className="h-4 w-1/2" />
              </div>
              <div className="p-4 border-t border-gray-100">
                <Skeleton className="h-4 w-3/4 mb-2" />
                <Skeleton className="h-4 w-1/2" />
              </div>
            </>
          ) : (
            results.map((result) => (
              <button
                key={result.id}
                className="map-search-result-item"
                onClick={() => {
                  onResultSelect?.(result);
                  setIsOpen(false);
                }}
              >
                {result.title}
              </button>
            ))
          )}
        </div>
      )}
    </div>
  );
}
