"use client";

import postData from "@/api/post-data";
import PasswordInput from "@/app/ui/form/PassowrdInput";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { toastSuccess } from "@/services/custom-toast";
import useCart from "@/stores/cart";
import { zodResolver } from "@hookform/resolvers/zod";
import { useLocale, useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";

/**
 *  * @author: Ahmed Badran
 * Created At: 22-10-2024
 *
 * Edit By: Ahmed Badran
 * Edit At: 30-10-2024: Connect with server
 *
 * NewPassword component renders a form for resetting password.
 *
 * The form includes the following fields:
 * - password: required, min length of 8
 * - confirm_password: required, min length of 8, same as password
 *
 * The form is rendered as a vertical list of form fields with labels and
 * validation messages. The fields are rendered as input fields with a password
 * toggle button.
 *
 * The form is wrapped in a <Form> component from the `@radix-ui/react-form`
 * library, which provides a way to manage form state and validation.
 *
 * @returns {JSX.Element} The rendered NewPassword component.
 */
export default function NewPassword({ params: { code } }) {
  const t = useTranslations("new-password");
  const label = useTranslations("form-labels");
  const error = useTranslations("form-errors");
  const router = useRouter();
  const locale = useLocale();
  const { cart, clearCart, updateCart } = useCart();

  const form = useForm({
    resolver: zodResolver(
      z
        .object({
          password: z
            .string({ message: error("required") })
            .min(6, { message: error("min6") }),
          password_confirmation: z
            .string({ message: error("required") })
            .min(6, { message: error("min6") }),
        })
        .refine((data) => data.password === data.password_confirmation, {
          message: error("confirm-password"),
          path: ["password_confirmation"],
        })
    ),
  });

  const {
    setError,
    formState: { isSubmitting },
  } = form; // Form helpers
  async function onSubmit(data) {
    const formData = new FormData();
    formData.append("pin_code", code);
    formData.append("password", data.password);
    formData.append("password_confirmation", data.password_confirmation);
    const res = await postData({
      endPoint: "/reset/reset_password",
      body: formData,
      locale,
    });

    if (res.error) {
      for (const [key, value] of Object.entries(res.data)) {
        setError(
          key,
          {
            type: "server",
            message: value,
          },
          {
            shouldFocus: true,
          }
        );
      }
      return;
    }

    toastSuccess(res.message);
    router.replace("/sign-in");
  }

  return (
    <>
      <CustomBreadcrumb subs={true} />
      <section className="max-md:mx-4 mt-12 mb-20 rounded-lg p-4 md:p-8 shadow-lg md:w-1/2 mx-auto">
        <div className="space-y-2 mb-12">
          <h1 className="font-bold text-xl text-center md:text-2xl lg:text-3xl text-dark">
            {t("title")}
          </h1>
        </div>
        <Form {...form}>
          <form
            method="post"
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6"
          >
            <FormField
              name="password"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <PasswordInput
                      field={field}
                      placeholder={label("password")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              name="password_confirmation"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <PasswordInput
                      field={field}
                      placeholder={label("confirm-password")}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <SubmitButton text={t("reset-password")} loading={isSubmitting} />
          </form>
        </Form>
      </section>
    </>
  );
}
