import { Button } from '@/components/ui/button';
import { FormControl, FormField, FormItem } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Text } from '@/components/ui/text';
import CommonImage from '../CommonImage';
import { useRef } from 'react';
import { Control, FieldValues, Path } from 'react-hook-form';
import { FormElement } from '@/types/form-types';

interface FormInputProps<TFieldValues extends FieldValues> {
  name: Path<TFieldValues>; // required
  control: Control<TFieldValues>;
  element: FormElement;
}

export const FilterSearchInput = <TFieldValues extends FieldValues>({
  element,
  control,
  name,
}: FormInputProps<TFieldValues>) => {
  const inputRef = useRef<HTMLInputElement>(null);

  return (
    <Text className="filter-master-search p-4">
      <FormField
        name={name}
        control={control}
        render={({ field }) => (
          <FormItem className="w-full relative">
            <FormControl>
              <Input
                {...field}
                ref={(e) => {
                  field.ref(e);
                  inputRef.current = e;
                }}
                className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none pr-10"
                placeholder={element?.placeholder ?? element?.title}
                autoComplete="off"
              />
            </FormControl>
            <Button
              type="button"
              onClick={() => {
                field.onChange('');
                inputRef.current?.focus();
              }}
              className="clear-input"
              variant="ghost"
            >
              <CommonImage
                src="/main/cross-arrow.webp"
                width={12}
                height={12}
                alt="Close"
                classname="clear-icon"
              />
            </Button>
          </FormItem>
        )}
      />
    </Text>
  );
};
