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

import { editProfile } from "@/actions/editProfile"
import Header from "@/components/Profile/Header"
import Button from "@/components/TempDesignSystem/Button"
import Divider from "@/components/TempDesignSystem/Divider"
import Title from "@/components/TempDesignSystem/Text/Title"

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

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

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

const formId = "edit-profile"

export default function Form({ user }: EditFormProps) {
  const { formatMessage } = useIntl()
  /**
   * 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: {
      "address.city": user.address.city ?? "",
      "address.countryCode": user.address.countryCode ?? "",
      "address.streetAddress": user.address.streetAddress ?? "",
      "address.zipCode": user.address.zipCode ?? "",
      dateOfBirth: user.dateOfBirth,
      email: user.email,
      language: user.language,
      phoneNumber: user.phoneNumber,
      currentPassword: "",
      newPassword: "",
      retypeNewPassword: "",
    },
    mode: "all",
    resolver: zodResolver(editProfileSchema),
    reValidateMode: "onChange",
  })

  return (
    <FormProvider {...form}>
      <Header>
        <hgroup>
          <Title as="h4" color="red" level="h1">
            {formatMessage({ id: "Edit" })}
          </Title>
          <Title as="h4" color="burgundy" level="h2">
            {user.name}
          </Title>
        </hgroup>
        <div className={styles.btns}>
          <Button
            form={formId}
            intent="secondary"
            size="small"
            theme="base"
            type="reset"
          >
            {formatMessage({ id: "Discard changes" })}
          </Button>
          <Button
            disabled={!form.formState.isValid || form.formState.isSubmitting}
            form={formId}
            intent="primary"
            size="small"
            theme="base"
            type="submit"
          >
            {formatMessage({ id: "Save" })}
          </Button>
        </div>
      </Header>
      <Divider color="burgundy" opacity={8} />
      <form action={formAction} className={styles.form} id={formId}>
        <FormContent />
      </form>
    </FormProvider>
  )
}
