import { startCase } from "lodash-es";
import { useFormContext } from "react-hook-form";
import { ErrorMessage } from "@hookform/error-message";
import { dynamicFormFieldError, getFieldType } from "./data";
import { FieldProps } from "./FieldType";

const FormElement: React.FC<FieldProps> = (props) => {
  /* eslint-disable react/prop-types */
  const { fieldName, fieldLabel, withLabel = true, required, dynamic } = props;

  const {
    register,
    control,
    formState: { errors },
  } = useFormContext();

  const dynamicError = dynamicFormFieldError({ dynamic, errors });

  const { content, type } = getFieldType({ register, control, ...props });

  return (
    <div className="w-full">
      {type === "checkbox" ? (
        <>{content}</>
      ) : (
        <div className="flex flex-col gap-2 w-full">
          <label
            htmlFor={fieldName}
            className="flex gap-0.5 items-center font-semibold"
          >
            {withLabel && (fieldLabel || startCase(fieldName))}
            {withLabel && required && <span className="text-red-500">*</span>}
          </label>
          {content}
        </div>
      )}

      {dynamicError ? (
        <p className="text-sm text-red-500 mt-1">{dynamicError}</p>
      ) : (
        errors[fieldName] && (
          <ErrorMessage
            errors={errors}
            name={fieldName}
            render={({ message }) => (
              <p className="text-sm text-red-500 mt-1">{message}</p>
            )}
          />
        )
      )}
    </div>
  );
};

export default FormElement;
