import * as React from "react";

import { cn } from "@/lib/utils";
import { Controller } from "react-hook-form";

export interface InputProps
  extends React.InputHTMLAttributes<HTMLInputElement> {
  startIcon?: React.ReactNode;
  endIcon?: React.ReactNode;
  rounded?: string;
  hiderError?: boolean;
  control: any;
  name: string;
  handleChange?: (value: string, name: string) => void;
}

const Input = React.forwardRef<HTMLInputElement, InputProps>(
  (
    {
      className,
      type,
      name,
      startIcon,
      hiderError = false,
      endIcon,
      defaultValue,
      control,
      handleChange,
      ...props
    },
    ref
  ) => {
    const onChange = (e: any, field: any) => {
      field.onChange(e.target.value);
      handleChange?.(e.target.value, e.target.name);
    };
    return (
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        render={({ field, fieldState }) => {
          return (
            <>
              <div className={cn("relative")}>
                {startIcon ? (
                  <span className="absolute inset-y-0 left-3 flex items-center focus:outline-none">
                    {startIcon}
                  </span>
                ) : null}
                <input
                  {...field}
                  {...props}
                  type={type}
                  className={cn(
                    "flex h-12 w-full rounded border border-slate-200 bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-slate-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-800 dark:bg-primary-500 dark:ring-offset-primary-500 dark:placeholder:text-slate-400 dark:focus-visible:ring-slate-300",
                    startIcon && "pl-10",
                    className
                  )}
                  ref={ref}
                  onChange={(e) => onChange(e, field)}
                />
                {endIcon ? (
                  <span className="absolute inset-y-0 right-3 flex items-center focus:outline-none">
                    {endIcon}
                  </span>
                ) : null}
              </div>
              {fieldState?.error && !hiderError && (
                <small className="text-xs text-red-500">
                  {fieldState?.error?.message}
                </small>
              )}
            </>
          );
        }}
      />
    );
  }
);
Input.displayName = "Input";

export { Input };
