"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useMarriageProfileQuery } from "@/hooks/marriage/use-profile-main";
import {
  getSubmitPath,
  hasCompletedMarriageProfileBasics,
} from "@/lib/get-submit-path";
import { useHabibWebReady } from "@/hooks/use-habib-web-ready";
import SliderPage from "@/components/Componentes/slider-page";
import Button from "@/components/Componentes/button";
import { useI18n } from "@/translations/provider";
import { localizePath } from "@/translations/config";

export default function TermsRoute() {
  const { data: profile, isLoading, isError, refetch } = useMarriageProfileQuery();
  const router = useRouter();
  const { locale, dictionary: t } = useI18n();

  // Signal Flutter when profile data is available (or failed — the page
  // has its own loading/error UI so the cover can safely be removed).
  useHabibWebReady(!isLoading);

  useEffect(() => {
    if (!isLoading && profile) {
      if (
        profile.status !== "pending_onboarding" ||
        hasCompletedMarriageProfileBasics(profile)
      ) {
        const target = getSubmitPath(profile);
        if (target !== "/terms") {
          router.replace(localizePath(target, locale));
        }
      }
    }
  }, [profile, isLoading, router, locale]);

  if (isLoading) {
    return (
      <div className="flex h-[100dvh] items-center justify-center bg-[#F5F5F5]">
        <div className="size-8 animate-spin rounded-full border-4 border-[#F14B46] border-t-transparent" />
      </div>
    );
  }

  if (isError) {
    return (
      <div className="flex h-[100dvh] flex-col items-center justify-center p-4 bg-[#F5F5F5]">
        <p className="mb-4 text-center font-medium text-[#F14B46]">
          {t["Failed to load profile. Please try again."] || "Failed to load profile. Please try again."}
        </p>
        <div className="w-full max-w-[200px]">
          <Button onClick={() => refetch()}>
            {t["Retry"] || "Retry"}
          </Button>
        </div>
      </div>
    );
  }

  if (
    profile &&
    (profile.status !== "pending_onboarding" ||
      hasCompletedMarriageProfileBasics(profile))
  ) {
    // If target is /terms but status is not pending_onboarding, we should still not render SliderPage
    // to prevent showing Onboarding to users who already finished it but have an unknown status.
    return (
      <div className="flex h-[100dvh] items-center justify-center bg-[#F5F5F5]">
        <div className="size-8 animate-spin rounded-full border-4 border-[#F14B46] border-t-transparent" />
      </div>
    );
  }

  return <SliderPage />;
}
