import { useEffect, useRef, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Loader2 } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import { useAuth } from "@/shared/context/AuthContext";
import {
  isComplaintFaydaState,
} from "@/shared/utils/faydaOidc";
import {
  mapRegisterWithFaydaCitizen,
  persistFaydaRegistrationAuth,
} from "@/shared/utils/faydaAuthSession";
import {
  FaydaOidcError,
  verifyComplaintUser,
} from "../services/complaintVerificationService";
import {
  clearComplaintVerification,
  storeComplaintVerification,
} from "../utils/complaintVerificationStorage";
import { COMPLAINT_RECORDS_PATH } from "../utils/complaintRoutes";

export default function ComplaintCallbackPage() {
  const { t, i18n } = useTranslation();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { setUser, setSelectedPositionId } = useAuth();
  const [error, setError] = useState<string | null>(null);
  const hasRun = useRef(false);

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

    const code = searchParams.get("code");
    const state = searchParams.get("state");
    const oidcError = searchParams.get("error");
    const oidcErrorDescription = searchParams.get("error_description");

    if (oidcError) {
      clearComplaintVerification();
      const message =
        oidcErrorDescription ||
        t("complaint.fayda.verificationFailed");
      setError(message);
      return;
    }

    if (!code) {
      clearComplaintVerification();
      setError(t("complaint.fayda.missingCode"));
      return;
    }

    if (state && !isComplaintFaydaState(state)) {
      clearComplaintVerification();
      setError(t("complaint.fayda.verificationFailed"));
      return;
    }

    const processCallback = async () => {
      try {
        const result = await verifyComplaintUser(
          { code, state },
          i18n.language,
        );

        if (!result.verified || !result.registration) {
          throw new Error(t("complaint.fayda.verificationFailed"));
        }

        const profile = await persistFaydaRegistrationAuth(result.registration);
        if (profile) {
          setUser(profile);
          const firstPositionId =
            profile.employee?.[0]?.positions?.[0]?.employeePositionId;
          if (firstPositionId) {
            setSelectedPositionId(firstPositionId);
          }
        }

        const citizen = mapRegisterWithFaydaCitizen(
          result.registration,
          i18n.language,
          profile,
        );

        if (!citizen.fullName && !profile) {
          throw new FaydaOidcError("FAYDA_PROFILE_INCOMPLETE");
        }

        storeComplaintVerification({
          verified: true,
          method: "fayda",
          citizen,
          verifiedAt: result.verifiedAt,
        });

        navigate(COMPLAINT_RECORDS_PATH, {
          replace: true,
          state: { fromComplaintVerification: true },
        });
      } catch (err: unknown) {
        clearComplaintVerification();
        if (err instanceof FaydaOidcError) {
          const translationKey = `complaint.fayda.errors.${err.code}`;
          const translated = t(translationKey);
          setError(
            translated !== translationKey
              ? translated
              : t("complaint.fayda.verificationFailed"),
          );
          return;
        }

        const message =
          err instanceof Error
            ? err.message
            : t("complaint.fayda.verificationFailed");
        setError(message);
      }
    };

    processCallback();
  }, [
    searchParams,
    navigate,
    t,
    i18n.language,
    setUser,
    setSelectedPositionId,
  ]);

  if (error) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-red-50 px-4">
        <p className="text-red-600 mb-4 text-center max-w-md">{error}</p>
        <Button
          onClick={() =>
            navigate(
              `/complaints?error=${encodeURIComponent(error)}`,
              { replace: true },
            )
          }>
          {t("complaint.fayda.backToComplaints")}
        </Button>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col items-center justify-center bg-white">
      <Loader2 className="h-10 w-10 text-primary animate-spin mb-4" />
      <p className="text-primary text-lg font-medium text-center px-4">
        {t("complaint.fayda.verifying")}
      </p>
    </div>
  );
}
