"use client";

import FloatingLabelInput from "../floatingLabelInput"
import { FormProps } from "#/types"
import { FormEvent, useState } from "react"

export default function Form({
    fields,
    submit,
    className,
    child,
    title,
    schema
} : FormProps) {
    const [errors, setErrors] = useState<Record<string, string>>({});

    const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()

        const formData = new FormData(e.currentTarget)
        const data = Object.fromEntries(formData)

        console.log("FORM DATA = ", data)
        const result = schema.safeParse(data);
        console.log("ZOD = ", result.error?.format())

        if(!result.success) {
            const formatedErrors = result.error.format() as Record<string, { _errors?: string[] }>;

            const newErrors: Record<string, string> = {};
            Object.keys(formatedErrors).forEach((field) => {
                if (field !== "_errors" && formatedErrors[field]._errors?.length) {
                  newErrors[field] = formatedErrors[field]._errors[0]; 
                }
            });

            setErrors(newErrors)
        } else {
            setErrors({})
            submit(result.data)
        }
    }

    return (
        <form className={className} onSubmit={handleSubmit}>
            <div className="flex justify-center text-black">
                <p className="text-3xl font-bold">{title}</p>
            </div>

            <div className="flex flex-col gap-8 mt-2">

                {
                    fields.map((item, index) => (
                        <div key={index}>
                            <FloatingLabelInput 
                                label={item.label} 
                                name={item.name} 
                                type={item.type} 
                                button={item.button}
                                defaultValue={item.defaultValue}
                                options={item.options}
                                placeholder={item.placeholder}
                                showPasswordToggle={item.showPasswordToggle}
                            />

                            <span className="text-red-500 text-xs mt-1">{errors[item.name]}</span>
                        </div>
                    ))
                }
            {child}
            </div>
        </form>

    )
}