import { Field, FormikProps, FormikValues } from 'formik';
import React, { ReactNode } from 'react';

// Assuming you want to make this component generic for any form values
interface InputFormProps<T = FormikValues> {
    formikProps: FormikProps<T>;
    name: keyof T & string;
    title: string;
    placeholder: string;
    iconRight?: ReactNode;
    iconLeft?: ReactNode;
    props?: React.InputHTMLAttributes<HTMLInputElement>;
    className?: string;
}

export const InputForm = <T extends FormikValues>({
    formikProps,
    name,
    title,
    placeholder,
    iconLeft,
    iconRight,
    props,
    className
}: InputFormProps<T>): React.ReactElement => {
    let pathArr = name.split('.');
    let errorValue = pathArr.reduce((prev: any, curr) => prev && prev[curr], formikProps.errors);
    let touchedValue = pathArr.reduce((prev: any, curr) => prev && prev[curr], formikProps.touched);

    return (
        <div
            className={`mb-3 w-full ${formikProps.submitCount ? (errorValue && touchedValue ? 'has-error' : '') : ''}`}>
            <label className="text-black text-opacity-60  font-normal font-['Alexandria'] leading-[18px]" htmlFor={name}>{title}</label>
            <div className="relative w-full">
                <div>
                    {iconRight}
                </div>
                <div>
                    {iconLeft}
                </div>
                <Field {...props} name={name} id={name} placeholder={placeholder}
                    className={`${className} form-input text-sm font-normal ${iconLeft && "px-10"}`} />
            </div>
            {formikProps.submitCount ?
                (errorValue && touchedValue ?
                    <div className="mt-[2px] w-full p-1 text-sm text-danger">{errorValue}</div> : <></>
                )
                :
                <> </>
            }
        </div>
    );
};
