'use client';

import { Input } from '@admin/components/ui/input';
import { cn } from '@admin/utils/common';
import { useState } from 'react';
import { Controller, useFormContext } from 'react-hook-form';

interface SearchFieldProps {
    name: string;
    placeholder?: string;
    disabled?: boolean;
    className?: string;
    onSearch?: (value: string) => void;
    suggestions?: string[];
}

export const SearchField = ({ name, placeholder, disabled, className, onSearch, suggestions }: SearchFieldProps) => {
    const [showSuggestions, setShowSuggestions] = useState(false);
    const { control } = useFormContext();

    return (
        <Controller
            control={control}
            name={name}
            render={({ field }) => (
                <div className="relative">
                    <Input
                        {...field}
                        type="search"
                        placeholder={placeholder}
                        disabled={disabled}
                        className={cn(className)}
                        value={field.value || ''}
                        onChange={(e) => {
                            field.onChange(e);
                            setShowSuggestions(true);
                            onSearch?.(e.target.value);
                        }}
                        onBlur={() => {
                            field.onBlur();
                            setTimeout(() => setShowSuggestions(false), 200);
                        }}
                        onFocus={() => setShowSuggestions(true)}
                    />
                    {showSuggestions && suggestions && suggestions.length > 0 && (
                        <div className="absolute top-full right-0 left-0 z-10 mt-1 max-h-60 overflow-auto rounded-md border bg-white shadow-lg">
                            {suggestions.map((suggestion, index) => (
                                <button
                                    key={index}
                                    type="button"
                                    className="w-full px-3 py-2 text-left hover:bg-gray-50 focus:bg-gray-50 focus:outline-none"
                                    onClick={() => {
                                        field.onChange(suggestion);
                                        setShowSuggestions(false);
                                    }}
                                >
                                    {suggestion}
                                </button>
                            ))}
                        </div>
                    )}
                </div>
            )}
        />
    );
};
