"use client";
import AppButton from "@/components/ui/button";
import { FormItem, FormWrapper } from "@/components/ui/form";
import AppInput from "@/components/ui/input";
import { useRouter } from "@/i18n/routing";
import { doChangePassword } from "@/lib/redux/features/auth";
import { useAppDispatch } from "@/lib/redux/hooks";
import StorageHelper from "@/lib/storeHelper";
import { hashMD5 } from "@/lib/utils";
import { ChangePasswordResponse } from "@/types/auth";
import { ResponseStatus, STORAGE_KEYS } from "@/types/common";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

type ChangePasswordFormProps = {
  handleCloseChangePasswordModal: () => void;
};
export default function ChangePasswordForm({
  handleCloseChangePasswordModal,
}: ChangePasswordFormProps) {
  const router = useRouter();
  const t = useTranslations("Form");
  const dispatch = useAppDispatch();

  const [isLoading, setIsLoading] = useState(false);

  const formSchema = z
    .object({
      oldPassword: z
        .string()
        .min(1, { message: t("validate.required", { length: 1 }) })
        .max(32, { message: t("validate.max_length_32") })
        .refine((value) => !/\s/.test(value), {
          message: t("validate.password_no_spaces"),
        }),
      newPassword: z
        .string()
        .min(1, { message: t("validate.required", { length: 1 }) })
        .max(32, { message: t("validate.max_length_32") })
        .refine((value) => !/\s/.test(value), {
          message: t("validate.password_no_spaces"),
        }),
      confirmPassword: z
        .string()
        .min(1, { message: t("validate.required", { length: 1 }) })
        .max(32, { message: t("validate.max_length_32") })
        .refine((value) => !/\s/.test(value), {
          message: t("validate.password_no_spaces"),
        }),
    })
    .refine((data) => data.newPassword === data.confirmPassword, {
      message: t("validate.passwords_must_match"),
      path: ["confirmPassword"],
    });

  type ChangePasswordFormSchema = z.infer<typeof formSchema>;

  const changePasswordForm = useForm<ChangePasswordFormSchema>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      oldPassword: "",
      newPassword: "",
      confirmPassword: "",
    },
  });

  async function onSubmit(values: ChangePasswordFormSchema) {
    try {
      setIsLoading(true);
      const data = {
        oldPassword: hashMD5(values.oldPassword),
        newPassword: hashMD5(values.newPassword),
        confirmPassword: hashMD5(values.confirmPassword),
      };
      const result = await dispatch(doChangePassword(data));
      const payload = result?.payload as ChangePasswordResponse;
      if (payload && payload.status === ResponseStatus.SUCCESS) {
        handleCloseChangePasswordModal();
        StorageHelper.removeCookie(STORAGE_KEYS.token);
        StorageHelper.removeLocalItem(STORAGE_KEYS.user);
        router.push("/sign-in");
      }
    } catch (error) {
      console.log("Change password error:", error);
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <FormWrapper<ChangePasswordFormSchema>
      form={changePasswordForm}
      onSubmit={onSubmit}
      layout="vertical"
      className="space-y-4"
    >
      <FormItem name="oldPassword" label={t("old_password")}>
        {({ value, ref, ...field }) => (
          <AppInput
            ref={ref}
            inputType="password"
            value={value}
            {...field}
            placeholder={t("old_password_placeholder")}
          />
        )}
      </FormItem>

      <FormItem name="newPassword" label={t("new_password")}>
        {({ value, ref, ...field }) => (
          <AppInput
            ref={ref}
            inputType="password"
            value={value}
            {...field}
            placeholder={t("new_password_placeholder")}
          />
        )}
      </FormItem>

      <FormItem name="confirmPassword" label={t("confirm_password")}>
        {({ value, ref, ...field }) => (
          <AppInput
            ref={ref}
            inputType="password"
            value={value}
            {...field}
            placeholder={t("confirm_password_placeholder")}
          />
        )}
      </FormItem>

      <div className="flex justify-end items-center gap-2">
        <AppButton
          type="default"
          loading={isLoading}
          onClick={handleCloseChangePasswordModal}
          className="w-fit"
        >
          {t("button.cancel")}
        </AppButton>
        <AppButton
          type="primary"
          htmlType="submit"
          loading={isLoading}
          className="w-fit"
        >
          {t("button.save")}
        </AppButton>
      </div>
    </FormWrapper>
  );
}
