"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useForm, type Resolver } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string } from "yup";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { useAuthStore } from "@/lib/auth/store";
import type { AuthInfo } from "@/lib/auth/store";
import { resolveAuthDeviceId } from "@/lib/firebase/authDeviceId";
import {
  markFcmTokenSynced,
  messageForFcmTokenFailure,
} from "@/lib/firebase/messaging";
import { refreshUnreadNotificationCount } from "@/lib/notifications/count";

interface VerifyCodeData {
  code: string;
}

export default function VerifyCodeForm() {
  const router = useRouter();
  const pendingLogin = useAuthStore((s) => s.pendingLogin);
  const setAuth = useAuthStore((s) => s.setAuth);
  const setPendingLogin = useAuthStore((s) => s.setPendingLogin);
  const clearPendingLogin = useAuthStore((s) => s.clearPendingLogin);
  const _hydrated = useAuthStore((s) => s._hydrated);

  // Protect the route: if we have hydrated and there's no pending login, redirect back
  useEffect(() => {
    if (_hydrated && !pendingLogin) {
      router.replace("/login");
    }
  }, [_hydrated, pendingLogin, router]);

  // Request notification permission and cache device_id as soon as the page opens.
  useEffect(() => {
    if (!_hydrated || !pendingLogin) {
      return;
    }

    let active = true;

    void (async () => {
      const deviceResult = await resolveAuthDeviceId({
        cachedDeviceId: pendingLogin.device_id,
        requestPermission: true,
      });

      if (!active) {
        return;
      }

      if (deviceResult.token && deviceResult.token !== pendingLogin.device_id) {
        setPendingLogin({
          ...pendingLogin,
          device_id: deviceResult.token,
        });
      }
    })();

    return () => {
      active = false;
    };
  }, [_hydrated, pendingLogin?.email, setPendingLogin]);

  const schema = object({
    code: string()
      .required("الرجاء إدخال رمز التحقق")
      .length(6, "رمز التحقق يجب أن يكون 6 أرقام"),
  });

  const {
    register,
    handleSubmit: rhfSubmit,
    formState: { errors },
  } = useForm<VerifyCodeData>({
    resolver: yupResolver(schema) as Resolver<VerifyCodeData>,
    defaultValues: { code: "" },
  });

  const [loading, setLoading] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [error, setError] = useState("");
  const [successMsg, setSuccessMsg] = useState("");

  const onSubmit = async (data: VerifyCodeData) => {
    // pendingLogin is guaranteed by the render gate below.
    const login = pendingLogin!;
    setError("");
    setSuccessMsg("");
    const deviceResult = await resolveAuthDeviceId({
      cachedDeviceId: login.device_id,
      requestPermission: true,
    });
    const device_id = deviceResult.token;
    if (!device_id) {
      setError(messageForFcmTokenFailure(deviceResult.reason));
      return;
    }

    setLoading(true);
    await apiFetch<AuthInfo>("/provider/verify-login", {
      method: "POST",
      body: JSON.stringify({
        email: login.email,
        code: data.code,
        device_type: "web",
        device_id,
        mac_address: "mac", // using "mac" as per payload requirement
        preferred_locale: "ar", // defaults to ar
      }),
      successCase: (res) => {
        if (res.data) {
          markFcmTokenSynced(device_id);
          setAuth(res.data);
          clearPendingLogin();
          void refreshUnreadNotificationCount();
          router.replace("/");
        }
      },
      errorCase: (res) => {
        setError(formatApiMsg(res.msg) || "رمز التحقق غير صحيح، حاول مرة أخرى");
      },
    });
    setLoading(false);
  };

  const onResend = async () => {
    // pendingLogin is guaranteed by the render gate below.
    const login = pendingLogin!;
    setError("");
    setSuccessMsg("");
    const deviceResult = await resolveAuthDeviceId({
      cachedDeviceId: login.device_id,
      requestPermission: true,
    });
    const device_id = deviceResult.token;
    if (!device_id) {
      setError(messageForFcmTokenFailure(deviceResult.reason));
      return;
    }

    setResendLoading(true);
    await apiFetch<AuthInfo>("/provider/login", {
      method: "POST",
      body: JSON.stringify({
        email: login.email,
        password: login.password,
        device_type: "web",
        device_id,
      }),
      needVerifyCase: () => {
        setSuccessMsg("تم إرسال رمز التحقق مرة أخرى إلى بريدك الإلكتروني");
      },
      errorCase: (res) => {
        setError(formatApiMsg(res.msg) || "تعذّر إرسال الرمز، حاول مرة أخرى");
      },
    });
    setResendLoading(false);
  };

  // Prevent flash of content before hydration
  if (!_hydrated || !pendingLogin) {
    return null;
  }

  return (
    <div className="flex flex-col w-full">
      <div className="text-right mb-8">
        <h2 className="text-white font-bold text-[30px] leading-9 mb-2">
          التحقق من الحساب 🔐
        </h2>
        <p className="text-gray-400 text-sm">
          أدخل رمز التحقق المكون من 6 أرقام المرسل إليك
        </p>
      </div>

      <form onSubmit={rhfSubmit(onSubmit)} className="flex flex-col gap-4">
        {/* Code Input */}
        <div>
          <label
            htmlFor="verify-code"
            className="text-gray-400 text-xs text-right block mb-2"
          >
            رمز التحقق
          </label>
          <div className="relative">
            <input
              id="verify-code"
              type="text"
              maxLength={6}
              {...register("code")}
              placeholder="123456"
              className={`w-full bg-[#13151A] border text-white text-sm rounded-xl px-4 py-4 pr-12 outline-none transition-colors text-center tracking-[0.5em] font-mono placeholder-gray-600 ${
                errors.code
                  ? "border-red-500/60 focus:border-red-500"
                  : "border-white/10 focus:border-[#FCD704]/50"
              }`}
              dir="ltr"
            />
            <div className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center pointer-events-none">
              <i className="ri-shield-keyhole-line text-gray-500 text-base" />
            </div>
          </div>
          {errors.code && (
            <p className="text-red-400 text-xs mt-1.5 text-right">
              {errors.code.message}
            </p>
          )}
        </div>

        {/* Server Messages */}
        {error && (
          <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-3 text-center">
            <p className="text-red-400 text-sm">{error}</p>
          </div>
        )}
        {successMsg && (
          <div className="bg-green-500/10 border border-green-500/30 rounded-xl p-3 text-center">
            <p className="text-green-400 text-sm">{successMsg}</p>
          </div>
        )}

        {/* Submit Button */}
        <button
          type="submit"
          disabled={loading || resendLoading}
          className="w-full bg-[#FCD704] text-[#13151A] font-bold text-base py-4 rounded-xl cursor-pointer whitespace-nowrap mt-2 transition-all hover:bg-[#FCD704]/90 disabled:opacity-70 flex items-center justify-center gap-2"
        >
          {loading ? (
            <>
              <i className="ri-loader-4-line animate-spin text-lg" />
              <span>جاري التحقق...</span>
            </>
          ) : (
            <span>تأكيد الرمز</span>
          )}
        </button>

        {/* Resend Code Button */}
        <button
          type="button"
          onClick={onResend}
          disabled={resendLoading || loading}
          className="w-full bg-transparent border border-white/10 text-white font-bold text-sm py-4 rounded-xl cursor-pointer whitespace-nowrap mt-2 transition-all hover:bg-white/5 disabled:opacity-70 flex items-center justify-center gap-2"
        >
          {resendLoading ? (
            <>
              <i className="ri-loader-4-line animate-spin text-lg" />
              <span>جاري الإرسال...</span>
            </>
          ) : (
            <span>إعادة إرسال الرمز</span>
          )}
        </button>
      </form>
    </div>
  );
}
