import * as React from "react";

import { cn } from "@/lib/utils";
import { Controller } from "react-hook-form";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "./input-otp";

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

const OTPInput = React.forwardRef<HTMLInputElement, InputProps>(
  (
    {
      className,
      type,
      name,
      otpLength = 4,
      hiderError = false,
      defaultValue,
      control,
      handleChange,
    },
    ref
  ) => {
    const onChange = (value: string, field: any) => {
      field.onChange(value);
      handleChange?.(value, name);
    };
    return (
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        render={({ field, fieldState }) => {
          return (
            <>
              <div className={cn("relative", className)}>
                <InputOTP
                  maxLength={otpLength}
                  {...field}
                  onChange={(value) => onChange(value, field)}
                >
                  {Array(otpLength)
                    .fill(null)
                    .map((_, index) => (
                      <InputOTPGroup key={index}>
                        <InputOTPSlot index={index} />
                      </InputOTPGroup>
                    ))}
                </InputOTP>
              </div>
              {fieldState?.error && !hiderError && (
                <small className="text-xs text-red-500">
                  {fieldState?.error?.message}
                </small>
              )}
            </>
          );
        }}
      />
    );
  }
);
OTPInput.displayName = "OTPInput";

export { OTPInput };
