/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import AuthHead from "@/components/auth/AuthHead";
import AuthPasswordInput from "@/components/auth/AuthPasswordInput";
import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import React, { useMemo } from "react";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import { IVerifyOtp } from "@/types/types";
import AuthNextButton from "@/components/auth/AuthNextButton";
import { useUser } from "@/hooks/useUser";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

function PasswordPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const user = useUser();
  const { request, loading } = useAxios();
  const authProvider =
    typeof window !== "undefined"
      ? localStorage.getItem("auth_provider")
      : null;
  const isGoogleUser = authProvider === "google" || user?.auth_provider === "google";

  const schema = useMemo(
    () =>
      yup.object().shape({
        password: yup
          .string()
          .required(t("settings.edit.password.required"))
          .min(8, t("settings.edit.password.minLength"))
          .matches(
            /^(?=.*[a-zA-Zآ-ی])(?=.*\d).{8,}$/,
            t("settings.edit.password.mustIncludeLettersNumbers")
          ),
        confirmPassword: yup
          .string()
          .required(t("settings.edit.password.repeatRequired"))
          .oneOf([yup.ref("password")], t("settings.edit.password.repeatMismatch"))
          .required(t("settings.edit.password.repeatRequiredField")),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      password: "",
      confirmPassword: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        (await request("PATCH", "/login/change_password", {
          ...(user?.mobile ? { mobile: user.mobile } : {}),
          new_password: values.password,
        })) as IVerifyOtp;
        toast.success(
          isGoogleUser
            ? t("settings.edit.password.setSuccess")
            : t("settings.edit.password.changeSuccess")
        );
        router.push("/settings/edit");
      } catch (err: any) {
        console.log("Unhandled error:", err?.message);
      }
    },
  });

  return (
    <LocalePageShell>
      <Container>
        <div className="p-4 flex flex-col items-center h-screen justify-center">
          <AuthHead
            title={
              isGoogleUser
                ? t("settings.edit.password.setTitle")
                : t("settings.edit.password.changeTitle")
            }
          />
          {isGoogleUser && (
            <p className="text-sm text-gray-500 text-center mb-4 max-w-sm">
              {t("settings.edit.password.googleHint")}
            </p>
          )}
          <form
            onSubmit={formik.handleSubmit}
            className="w-full max-w-sm flex flex-col items-center"
          >
            <AuthPasswordInput
              name="password"
              placeholder={t("settings.edit.password.placeholder")}
              wrapperClassName="mt-4"
              className={`border ${
                formik.touched.password && formik.errors.password
                  ? "border-red-500 dark:border-red-500"
                  : "border-gray-300"
              }`}
              value={formik.values.password}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.touched.password && formik.errors.password && (
              <small className="text-red-500 mt-2 block">
                {formik.errors.password}
              </small>
            )}

            <AuthPasswordInput
              name="confirmPassword"
              placeholder={t("settings.edit.password.repeatPlaceholder")}
              wrapperClassName="mt-4"
              className={`border ${
                formik.touched.confirmPassword && formik.errors.confirmPassword
                  ? "border-red-500 dark:border-red-500"
                  : "border-gray-300"
              }`}
              value={formik.values.confirmPassword}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.touched.confirmPassword && formik.errors.confirmPassword && (
              <small className="text-red-500 mt-2 block">
                {formik.errors.confirmPassword}
              </small>
            )}

            <AuthNextButton type="submit" className="mt-20" loading={loading} disabled={loading}>
              {t("settings.edit.password.confirm")}
            </AuthNextButton>
          </form>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default PasswordPage;
