"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,
  formClassName
}: 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 onSubmit={handleSubmit} className={(formClassName) + " form-container"}>
      <div className="form-title d-flex justify-content-center text-black mb-3 ">
        <p className="fs-3 fw-bold">{title}</p>
      </div>

      <div className={`d-flex flex-column form-fields ${className}`}>

        {
          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="form-error">{errors[item.name]}</span>
            </div>
          ))
        }
      </div>
      {child}
    </form>
  )
}