"use client";

import { useRegisterExternalPortalUser } from "@/external-portal/hooks/useRegisterExternalPortalUser";
import { Button } from "@/shared/common/ui/button";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { getDefaultFaydaRedirectUri } from "@/shared/utils/faydaOidc";
import { persistFaydaRegistrationAuth } from "@/shared/utils/faydaAuthSession";
import { Loader2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useSearchParams } from "react-router-dom";
import { toast } from "sonner";

export default function ExternalPortalCallback() {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { handleError } = useErrorHandler(t);
  const { isFayidaRegistering, registerExternalFayidaUser } =
    useRegisterExternalPortalUser();
  const hasRun = useRef(false);

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

    const code = searchParams.get("code");
    const state = searchParams.get("state");

    if (!code) {
      toast.error("Missing authorization code");
      setError("Missing authorization code");
      setLoading(false);
      navigate("/external-portal/signin", { replace: true });
      return;
    }

    const loginWithFayda = async () => {
      try {
        const res = await registerExternalFayidaUser({
          code,
          redirectUri: getDefaultFaydaRedirectUri(),
        });

        if (!res || !res.response?.data) {
          throw new Error("Invalid response from Fayda login");
        }

        const data = res.response.data;
        const userId = data?.userId ?? data?.user?.id ?? data?.user?.userId;
        const token = data?.token;
        const refreshToken = data?.refreshToken;

        if (!userId) {
          throw new Error("Failed to get user ID from server.");
        }

        await persistFaydaRegistrationAuth({
          ...data,
          token,
          refreshToken,
        });

        navigate(`/verify-otp?userId=${userId}&isExternalOrg=false`, {
          replace: true,
        });
      } catch (err: unknown) {
        console.error("LoginWithFayda error:", err);
        handleError(err);
        setError(
          err instanceof Error
            ? err.message
            : t("registration.auth.faydaSigninFailed"),
        );
      } finally {
        setLoading(false);
      }
    };

    loginWithFayda();
  }, [searchParams, navigate, handleError, registerExternalFayidaUser, t]);

  if (loading || isFayidaRegistering) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-white">
        <Loader2 className="h-10 w-10 text-primary-600 animate-spin mb-4" />
        <p className="text-primary-700 text-lg font-medium">
          {t("registration.auth.faydaProcessing")}
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-red-50">
        <p className="text-red-600 mb-4">{error}</p>
        <Button
          onClick={() =>
            navigate("/external-portal/signin", { replace: true })
          }>
          {t("registration.auth.backToAuth")}
        </Button>
      </div>
    );
  }

  return null;
}
