"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect } from "react"
import { useFormState as useReactFormState } from "react-dom"
import { FormProvider, useForm } from "react-hook-form"

import { useProfileStore } from "@/stores/edit-profile"

import { editProfile } from "@/actions/editProfile"

import FormContent from "./Content"
import { type EditProfileSchema, editProfileSchema } from "./schema"

import styles from "./form.module.css"

import {
  type EditFormProps,
  type State,
} from "@/types/components/myPages/myProfile/edit"

export default function Form({ user }: EditFormProps) {
  const isValid = useProfileStore((store) => store.valid)
  const setValid = useProfileStore((store) => store.setValid)
  /**
   * like react, react-hook-form also exports a useFormState hook,
   * we want to clearly keep them separate by naming.
   */
  const [state, formAction] = useReactFormState<State, FormData>(
    editProfile,
    null
  )

  const form = useForm<EditProfileSchema>({
    defaultValues: user,
    criteriaMode: "all",
    mode: "onTouched",
    resolver: zodResolver(editProfileSchema),
    reValidateMode: "onChange",
  })

  useEffect(() => {
    if (isValid !== form.formState.isValid) {
      setValid(form.formState.isValid)
    }
  }, [form.formState.isValid, isValid, setValid])

  return (
    <FormProvider {...form}>
      <form action={formAction} className={styles.form} id="edit-profile">
        <FormContent control={form.control} />
      </form>
    </FormProvider>
  )
}
