'use client';
import {
  FieldValues,
  Path,
  RegisterOptions,
  UseFormReturn,
} from 'react-hook-form';
import SelectTemplate, { Props as SelectTemplateProps } from 'react-select';
import { cn } from '../../../helper/cn';
import dynamic from 'next/dynamic';

interface SelectProps<T extends FieldValues> {
  name: Path<T>;
  form: UseFormReturn<T>;
  formOptions?: RegisterOptions<T>;
  label?: string;
  placeholder?: string;
  className?: string;
}

const SelectCom = <T extends FieldValues>({
  name,
  label = name,
  placeholder = label,
  form,
  formOptions,
  className,
  ...inputProps
}: SelectProps<T>) => {
  return (
    <div>
      <span className="label-text text-lg flex items-center gap-2">
        {label}
      </span>
      <SelectTemplate
        {...form.register(name, formOptions)}
        onChange={(newValue: any) => {
          if ('value' in newValue) {
            form.setValue(name, newValue.value);
          } else {
            form.setValue(name, newValue);
          }
          form.trigger(name);
        }}
        className={cn('w-full placeholder:text-neutral-600', className)}
        placeholder={placeholder}
        {...inputProps}
      />
      {form.formState.errors[name] && (
        <p className="text-error">
          {form.formState.errors[name].message as string}
        </p>
      )}
    </div>
  );
};

const SelectWrapper = (props: any) => <SelectCom {...props} />;

export const Select = dynamic(() => Promise.resolve(SelectWrapper), {
  ssr: false,
});
