"use client";

import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import {
  completeLogin,
  getAxiosErrorMessage,
  getLoginFailureMessage,
  parseLoginResponse,
} from "@/lib/auth/postLogin";
import type { IVerifyOtp } from "@/types/types";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type InstagramCallbackResponse = IVerifyOtp & {
  instagram_username?: string | null;
  instagram_bio?: string | null;
  instagram_profile_picture_url?: string | null;
};

export default function InstagramCallbackPage() {
  const { t, i18n } = useTranslation("common");
  const router = useRouter();
  const { request } = useAxios();
  const [status, setStatus] = useState<"working" | "error">("working");
  const ran = useRef(false);

  useEffect(() => {
    if (ran.current) return;
    ran.current = true;

    void handleCallback();

    async function handleCallback() {
      const params = new URLSearchParams(window.location.search);
      const code = params.get("code");
      const oauthError = params.get("error");
      const stateRaw = params.get("state");

      const storedMode = sessionStorage.getItem("ig_oauth_mode") || "login";
      const storedNonce = sessionStorage.getItem("ig_oauth_nonce") || "";
      sessionStorage.removeItem("ig_oauth_mode");
      sessionStorage.removeItem("ig_oauth_nonce");

      if (oauthError) {
        toast.error(t("auth.instagramLoginFailed"));
        setStatus("error");
        router.replace(storedMode === "link" ? "/settings/edit/instagram-import" : "/login");
        return;
      }

      let mode = storedMode;
      try {
        const parsedState = stateRaw
          ? (JSON.parse(decodeURIComponent(stateRaw)) as { mode?: string; nonce?: string })
          : null;
        if (parsedState?.mode) mode = parsedState.mode;
        if (!parsedState?.nonce || parsedState.nonce !== storedNonce) {
          throw new Error("nonce mismatch");
        }
      } catch {
        toast.error(t("auth.instagramLoginFailed"));
        setStatus("error");
        router.replace("/login");
        return;
      }

      if (!code) {
        toast.error(t("auth.instagramLoginFailed"));
        setStatus("error");
        router.replace(mode === "link" ? "/settings/edit/instagram-import" : "/login");
        return;
      }

      try {
        if (mode === "link") {
          await request("POST", "/auth/instagram/link", { code });
          toast.success(t("settings.edit.instagramImport.linkSuccess"));
          router.replace("/settings/edit/instagram-import");
          return;
        }

        const rawResponse = await request("POST", "/auth/instagram/callback", { code });
        const authResponse = parseLoginResponse(rawResponse) as InstagramCallbackResponse;
        const raw = rawResponse as Partial<InstagramCallbackResponse>;

        localStorage.setItem("auth_provider", "instagram");
        localStorage.removeItem("mobile");
        localStorage.removeItem("otp");
        if (raw?.instagram_username) {
          localStorage.setItem("instagram_username", raw.instagram_username);
        }
        if (raw?.instagram_bio) {
          localStorage.setItem("instagram_bio", raw.instagram_bio);
        }
        if (raw?.instagram_profile_picture_url) {
          localStorage.setItem(
            "instagram_profile_picture_url",
            raw.instagram_profile_picture_url
          );
        }

        const loggedIn = await completeLogin(router, authResponse);

        if (!loggedIn) {
          const detail = getLoginFailureMessage(
            rawResponse,
            i18n.language === "en" ? "en" : "fa"
          );
          toast.error(detail);
          setStatus("error");
          router.replace("/login");
        }
      } catch (err: unknown) {
        const data = (
          err as { response?: { data?: { message?: string } } }
        )?.response?.data;
        const message =
          data?.message ||
          getAxiosErrorMessage(err, i18n.language === "en" ? "en" : "fa");
        toast.error(message, { duration: 8000 });
        setStatus("error");
        router.replace(mode === "link" ? "/settings/edit/instagram-import" : "/login");
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <LocalePageShell>
      <div className="flex min-h-[60vh] flex-col items-center justify-center gap-3 text-center">
        <p className="text-sm text-neutral-500">
          {status === "working"
            ? t("auth.instagramConnecting")
            : t("auth.instagramLoginFailed")}
        </p>
      </div>
    </LocalePageShell>
  );
}
