import type { EmailField } from "@payloadcms/plugin-form-builder/types";
import type { FieldErrorsImpl, FieldValues, UseFormRegister } from "react-hook-form";

import React from "react";

import { Error } from "../Error";
import { Width } from "../Width";

export const Email: React.FC<
  {
    errors: Partial<
      FieldErrorsImpl<{
        [x: string]: any;
      }>
    >;
    register: UseFormRegister<any & FieldValues>;
  } & EmailField
> = ({ name, errors, label, register, required: requiredFromProps, width }) => {
  return (
    <Width width={width}>
      <div className="form-wrap">
        <input
          type="email"
          className="form-input"
          id={name}
          {...register(name, { pattern: /^\S[^\s@]*@\S+$/, required: requiredFromProps })}
        />
        <label className="form-label" htmlFor={name}>
          {label}
        </label>
        {requiredFromProps && errors[name] && <Error />}
      </div>
    </Width>
  );
};
