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

import { profile } from "@/constants/routes/myPages"

import { editProfile } from "@/actions/editProfile"
import Header from "@/components/Profile/Header"
import Button from "@/components/TempDesignSystem/Button"
import Link from "@/components/TempDesignSystem/Link"
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"
import type { Lang } from "@/constants/languages"

const formId = "edit-profile"

export default function Form({ user }: EditFormProps) {
  const { formatMessage } = useIntl()
  const params = useParams()
  const lang = params.lang as Lang
  /**
   * 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 methods = useForm<EditProfileSchema>({
    defaultValues: {
      address: {
        city: user.address.city ?? "",
        countryCode: user.address.countryCode ?? "",
        streetAddress: user.address.streetAddress ?? "",
        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 (
    <>
      <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 asChild intent="secondary" size="small" theme="base">
            <Link href={profile[lang]}>
              {formatMessage({ id: "Discard changes" })}
            </Link>
          </Button>
          <Button
            disabled={
              !methods.formState.isValid || methods.formState.isSubmitting
            }
            form={formId}
            intent="primary"
            size="small"
            theme="base"
            type="submit"
          >
            {formatMessage({ id: "Save" })}
          </Button>
        </div>
      </Header>
      <form action={formAction} className={styles.form} id={formId}>
        <FormProvider {...methods}>
          <FormContent />
        </FormProvider>
      </form>
    </>
  )
}
