"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/inputs/input";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/inputs/input-otp";
import { PhoneInput } from "@/components/ui/inputs/phone-input";
import { useAuthApi, type AuthChannel } from "@/hooks/use-auth-api";
import { getAuthErrorMessage } from "@/lib/auth-error";
import { useAuthStore } from "@/store/authStore";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useState } from "react";
import { toast } from "react-toastify";

export const ForgotPasswordForm = (): React.ReactNode => {
  const t = useTranslations("dashboard.auth");
  const tValidation = useTranslations("dashboard.auth.validation");
  const [verificationMethod, setVerificationMethod] = useState<AuthChannel | null>(
    null
  );
  const [selectedVerificationMethod, setSelectedVerificationMethod] =
    useState<AuthChannel | null>(null);
  const [contactValue, setContactValue] = useState("");
  const [otpValue, setOtpValue] = useState("");
  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");

  const {
    forgot,
    verifyOtp,
    resetPassword,
    isForgetting,
    isVerifyingOtp,
    isResettingPassword,
  } = useAuthApi();

  const {
    resetSteps,
    setResetSteps,
    setResetWith,
    resetWith,
    resetObj,
    setResetObj,
  } = useAuthStore();

  const resolvedMethod: AuthChannel | null =
    verificationMethod || resetObj?.channel || resetWith || null;

  const methodLabel =
    resolvedMethod === "email"
      ? t("email")
      : resolvedMethod === "whatsapp"
        ? t("whatsapp")
        : t("verificationMethod");

  const backHandler = () => {
    if (resetSteps === "otp") {
      setResetSteps("emailWhatsapp");
      return;
    }

    if (resetSteps === "newPassword") {
      setResetSteps("otp");
      return;
    }

    if (verificationMethod) {
      setVerificationMethod(null);
      return;
    }

    setResetSteps("resetWith");
  };

  const selectedVerificationMethodHandler = () => {
    if (!selectedVerificationMethod) return;
    setVerificationMethod(selectedVerificationMethod);
    setResetWith(selectedVerificationMethod);
  };

  const getContactIdentifier = (): string => {
    return contactValue.trim();
  };

  const handleForgotRequest = async () => {
    if (!resolvedMethod) return;

    const contactIdentifier = getContactIdentifier();
    if (!contactIdentifier) {
      toast.error(tValidation("emailRequired"));
      return;
    }

    try {
      await forgot({
        identifier: contactIdentifier,
        channel: resolvedMethod,
      });

      setResetObj({
        identifier: contactIdentifier,
        channel: resolvedMethod,
      });
      setResetWith(resolvedMethod);
      setResetSteps("otp");
      setOtpValue("");
    } catch (error: unknown) {
      toast.error(
        getAuthErrorMessage(error, "Failed to send reset request.")
      );
    }
  };

  const handleVerifyCode = async () => {
    if (!resolvedMethod) return;

    const identifier = resetObj?.identifier || getContactIdentifier();
    if (!identifier) {
      toast.error(tValidation("emailRequired"));
      return;
    }

    if (otpValue.length !== 6) {
      toast.error(tValidation("otpInvalid"));
      return;
    }

    try {
      await verifyOtp({
        identifier,
        code: otpValue,
        purpose: "password_reset",
      });

      setResetObj({
        identifier,
        channel: resolvedMethod,
        code: otpValue,
      });
      setResetSteps("newPassword");
    } catch (error: unknown) {
      toast.error(getAuthErrorMessage(error, "OTP verification failed."));
    }
  };

  const handleResetPassword = async () => {
    if (!resolvedMethod) return;

    if (password.length < 8) {
      toast.error(tValidation("passwordMin", { min: 8 }));
      return;
    }

    if (password !== passwordConfirmation) {
      toast.error(tValidation("passwordConfirmationMismatch"));
      return;
    }

    const identifier = resetObj?.identifier;
    const code = resetObj?.code;

    if (!identifier || !code) {
      toast.error(t("verificationIdMissing"));
      return;
    }

    try {
      await resetPassword({
        identifier,
        code,
        password,
        password_confirmation: passwordConfirmation,
      });

      setResetObj({
        identifier: undefined,
        channel: undefined,
        code: undefined,
      });
      setVerificationMethod(null);
      setSelectedVerificationMethod(null);
      setContactValue("");
      setOtpValue("");
      setPassword("");
      setPasswordConfirmation("");
      setResetSteps("resetWith");
    } catch (error: unknown) {
      toast.error(getAuthErrorMessage(error, "Password reset failed."));
    }
  };

  const formRenderer = () => {
    if (resetSteps === "newPassword") {
      return (
        <div className="flex w-full flex-col gap-6">
          <div className="flex w-full flex-col gap-2">
            <label className="font-sans text-base leading-[1.2] text-foreground">
              {t("password")}
            </label>
            <Input
              type="password"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              placeholder={t("passwordPlaceholder")}
              className="h-14 w-full rounded-xl border-border px-4 py-5  font-sans text-sm"
            />
          </div>

          <div className="flex w-full flex-col gap-2">
            <label className="font-sans text-base leading-[1.2] text-foreground">
              {t("passwordConfirmation")}
            </label>
            <Input
              type="password"
              value={passwordConfirmation}
              onChange={(event) => setPasswordConfirmation(event.target.value)}
              placeholder={t("passwordConfirmationPlaceholder")}
              className="h-14 w-full rounded-xl border-border px-4 py-5  font-sans text-sm"
            />
          </div>

          <Button
            type="button"
            size="xl"
            onClick={handleResetPassword}
            disabled={isResettingPassword}
            className="w-full font-sans disabled:cursor-not-allowed disabled:bg-primary-100"
          >
            <span className="text-sm font-bold leading-4 tracking-[-0.084px]">
              {t("resetPasswordAction")}
            </span>
            <Image
              src="/images/login/icons/arrow-left.svg"
              alt=""
              width={20}
              height={20}
            />
          </Button>
        </div>
      );
    }

    if (resetSteps === "otp") {
      return (
        <div className="flex w-full flex-col gap-6">
          <div className="flex flex-col items-center gap-2">
            <div className="flex items-center gap-2">
              <Image
                src="/images/login/icons/lock.svg"
                alt={t("lockIconAlt")}
                width={24}
                height={24}
              />
              <h4 className="font-sans text-xl font-bold leading-[1.2] text-foreground">
                {t("enterOtp")}
              </h4>
            </div>
            <p className="font-sans text-sm leading-[1.2] text-muted-foreground">
              {t("otpDescription", { method: methodLabel })}
            </p>
          </div>

          <div className="flex w-full flex-col items-center gap-4">
            <InputOTP
              maxLength={6}
              value={otpValue}
              onChange={(value) => setOtpValue(value.replace(/\D/g, ""))}
            >
              <InputOTPGroup>
                {Array.from({ length: 6 }).map((_, index) => (
                  <InputOTPSlot key={index} index={index} />
                ))}
              </InputOTPGroup>
            </InputOTP>

            <button
              type="button"
              onClick={handleForgotRequest}
              disabled={isForgetting}
              className="font-sans text-sm text-primary underline underline-offset-2 disabled:opacity-70"
            >
              {t("resendOtp")}
            </button>
          </div>

          <Button
            type="button"
            size="xl"
            onClick={handleVerifyCode}
            disabled={otpValue.length !== 6 || isVerifyingOtp}
            className="w-full font-sans disabled:cursor-not-allowed disabled:bg-primary-100"
          >
            <span className="text-sm font-bold leading-4 tracking-[-0.084px]">
              {t("next")}
            </span>
            <Image
              src="/images/login/icons/arrow-left.svg"
              alt=""
              width={20}
              height={20}
            />
          </Button>
        </div>
      );
    }

    if (verificationMethod === "whatsapp" || verificationMethod === "email") {
      return (
        <div className="flex w-full flex-col gap-6">
          <div className="flex w-full flex-col gap-2">
            <label className="font-sans text-base leading-[1.2] text-foreground">
              {verificationMethod === "email" ? t("email") : t("phone")}
            </label>

            {verificationMethod === "email" ? (
              <Input
                type="email"
                value={contactValue}
                onChange={(event) => setContactValue(event.target.value)}
                placeholder={t("emailPlaceholder")}
                className="h-14 w-full rounded-xl border-border px-4 py-5  font-sans text-sm"
              />
            ) : (
              <PhoneInput
                value={contactValue}
                onChange={setContactValue}
                placeholder="0000000"
              />
            )}
          </div>

          <Button
            type="button"
            size="xl"
            onClick={handleForgotRequest}
            disabled={isForgetting}
            className="w-full font-sans disabled:cursor-not-allowed disabled:bg-primary-100"
          >
            <span className="text-sm font-bold leading-4 tracking-[-0.084px]">
              {t("next")}
            </span>
            <Image
              src="/images/login/icons/arrow-left.svg"
              alt=""
              width={20}
              height={20}
            />
          </Button>
        </div>
      );
    }

    return (
      <div className="flex w-full flex-col gap-6">
        <div className="flex w-full flex-col gap-4">
          <p className="font-sans text-base leading-[1.2] text-foreground">
            {t("chooseVerificationMethod")}
          </p>

          <div className="flex w-full items-center gap-4">
            <Button
              type="button"
              variant={
                selectedVerificationMethod === "email"
                  ? "toggle-active"
                  : "toggle"
              }
              size="lg"
              onClick={() => setSelectedVerificationMethod("email")}
              className="rounded-xl px-4 py-4"
            >
              <Image
                src="/images/login/icons/email.svg"
                alt={t("email")}
                width={20}
                height={20}
              />
              <span className="font-sans text-sm leading-[1.2]">
                {t("email")}
              </span>
            </Button>

            <div className="font-sans text-sm text-muted-foreground">{t("or")}</div>

            <Button
              type="button"
              variant={
                selectedVerificationMethod === "whatsapp"
                  ? "toggle-active"
                  : "toggle"
              }
              size="lg"
              onClick={() => setSelectedVerificationMethod("whatsapp")}
              className="rounded-xl px-4 py-4"
            >
              <Image
                src="/images/login/icons/whatsapp.svg"
                alt={t("whatsapp")}
                width={20}
                height={20}
              />
              <span className="font-sans text-sm leading-[1.2]">
                {t("whatsapp")}
              </span>
            </Button>
          </div>
        </div>

        <Button
          type="button"
          size="xl"
          onClick={selectedVerificationMethodHandler}
          disabled={!selectedVerificationMethod}
          className="w-full font-sans disabled:cursor-not-allowed disabled:bg-primary-100"
        >
          <span className="text-sm font-bold leading-4 tracking-[-0.084px]">
            {t("next")}
          </span>
          <Image
            src="/images/login/icons/arrow-left.svg"
            alt=""
            width={20}
            height={20}
          />
        </Button>
      </div>
    );
  };

  return (
    <div className="flex h-full w-full flex-col items-center">
      <div className="flex w-full items-start justify-between md:px-20 px-5 pt-10">
        <div className="relative h-14 w-40">
          <Image
            alt={t("logoAlt")}
            fill
            className="max-w-none object-contain"
            src="/images/login/icons/maal co logo 1.svg"
          />
        </div>

        <div className="flex items-center gap-8 z-50">
          <Button
            variant="link"
            onClick={backHandler}
            className="flex items-center gap-2"
          >
            <Image
              src="/images/login/icons/arrow-right.svg"
              alt={t("back")}
              width={24}
              height={24}
            />
            <p className="font-sans text-base leading-normal text-muted-foreground">
              {t("back")}
            </p>
          </Button>
        </div>
      </div>

        <div className="flex w-full md:max-w-[876px] translate-y-[-40%] flex-col gap-12 md:px-20 px-10 pt-[calc(50vh-0.5px)]">
        <div className="flex w-full flex-col items-start gap-3">
          <div className="h-14 w-14 overflow-hidden">
            <Image
              alt={t("logoAlt")}
              src="/images/login/icons/maal co logo 1.svg"
              width={56}
              height={56}
            />
          </div>

          <div className="flex items-center justify-center gap-2">
            <h3 className="font-sans text-[28px] font-bold leading-[1.2] text-foreground">
              {t("forgotPasswordTitle")}
            </h3>
          </div>

          <p className="font-sans text-lg leading-[1.2] text-muted-foreground">
            {t("forgotPasswordSubtitle")}
          </p>
        </div>
        {formRenderer()}
      </div>
    </div>
  );
};
