"use client";

import { useTranslation } from "react-i18next";
import React, { useState } from "react";
import * as yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { error, success } from "@/components/alert";
import { useRouter } from "next/navigation";
import { Input } from "@/components/input";
import { Button } from "@/components/button";
import { authService } from "@/services/auth";
import { setCookie } from "cookies-next";
import useUserStore from "@/global-store/user";
import { isFirebaseConfigured } from "@/lib/firebase";
import { useMutation } from "@tanstack/react-query";
import { userService } from "@/services/user";
import { PasswordUpdateBody } from "@/types/user";
import NetworkError from "@/utils/network-error";

const schema = yup.object({
  password: yup.string().required(),
  password_confirmation: yup
    .string()
    .nullable()
    .oneOf([yup.ref("password"), null]),
});

type FormData = yup.InferType<typeof schema>;

interface ResetPasswordProps {
  phone?: string;
  verifyId?: string;
  verifyCode?: string;
}

const ResetPassword = ({ phone, verifyId, verifyCode }: ResetPasswordProps) => {
  const router = useRouter();
  const { t } = useTranslation();
  const localSignIn = useUserStore((state) => state.signIn);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { mutate, isLoading } = useMutation({
    mutationFn: (body: PasswordUpdateBody) => userService.updatePassword(body),
    onError: (err: NetworkError) => {
      error(err.message);
    },
  });
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FormData>({
    resolver: yupResolver(schema),
  });

  const handleUpdatePassword = async (data: FormData) => {
    const resolvedVerifyId = verifyId || sessionStorage.getItem("sms_verify_id") || "";
    const resolvedVerifyCode = verifyCode || sessionStorage.getItem("sms_verify_code") || "";
    const resolvedPhone =
      (phone || "").replace(/\D/g, "") || sessionStorage.getItem("sms_verify_phone") || "";

    if (!isFirebaseConfigured && resolvedVerifyId) {
      setIsSubmitting(true);
      try {
        const res = await authService.resetPasswordWithOtp({
          phone: resolvedPhone,
          password: data.password,
          password_confirmation: data.password_confirmation || data.password,
          verifyId: resolvedVerifyId,
          verifyCode: resolvedVerifyCode,
          type: "ippanel",
        });
        setCookie("token", `Bearer ${res.data.access_token}`);
        localSignIn(res.data.user);
        sessionStorage.removeItem("sms_verify_id");
        sessionStorage.removeItem("sms_verify_code");
        sessionStorage.removeItem("sms_verify_phone");
        success(t("successfully.updated"));
        router.replace("/");
      } catch (err: any) {
        error(err?.message || t("verify.error"));
      } finally {
        setIsSubmitting(false);
      }
      return;
    }

    mutate(data, {
      onSuccess: () => {
        success(t("successfully.updated"));
        router.replace("/");
      },
    });
  };

  return (
    <div className="flex flex-col gap-6  ">
      <h1 className="font-semibold text-[30px] mb-2 text-start">{t("reset.password")}</h1>
      <form id="reset" onSubmit={handleSubmit(handleUpdatePassword)}>
        <div className="flex flex-col gap-3 mb-8 w-full">
          <Input
            fullWidth
            {...register("password")}
            error={errors.password?.message}
            label={t("password")}
            type="password"
          />
          <Input
            fullWidth
            {...register("password_confirmation")}
            error={errors.password_confirmation?.message}
            label={t("password.confirmation")}
            type="password"
          />
        </div>
        <Button loading={isLoading || isSubmitting} fullWidth type="submit" form="reset">
          {t("reset")}
        </Button>
      </form>
    </div>
  );
};

export default ResetPassword;
