"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Button from "@/components/ui/button";
import NavigationButton from "@/components/ui/navigation-button";
import ReportActionsSheet from "@/components/ui/report-actions-sheet";
import { authBridge } from "@/lib/auth-bridge";
import { useMarriageProfileQuery } from "@/hooks/marriage/use-profile-main";
import type { MarriageProfileResponse } from "@/hooks/marriage/types";
import { localizePath } from "@/i18n/config";
import { useI18n } from "@/i18n/provider";

const REDIRECT_SESSION_KEY = "redirect";

function getSubmitPath(profile: MarriageProfileResponse | undefined) {
  const isInCase = profile?.status === "in_case";
  const isFemaleAcceptedFlow =
    isInCase &&
    (profile?.active_case?.status === "payment_pending" ||
      profile?.active_case?.status === "female_accepted" ||
      profile?.active_case?.status === "payment_done");

  return isFemaleAcceptedFlow
    ? "/request-accepted"
    : isInCase && profile?.active_case?.status === "male_accepted"
      ? "/request-sent"
      : profile?.status === "pending_onboarding"
        ? "/terms"
        : profile?.status === "pending_info"
          ? "/questions-list"
          : profile?.status === "waiting"
            ? "/finding-match"
            : profile?.status === "in_case" || profile?.status === "matched"
              ? "/new-match"
              : "/terms";
}

export default function Intro() {
  const router = useRouter();
  const { dictionary: t, locale } = useI18n();
  const { data: profile, refetch } = useMarriageProfileQuery({
    enabled: false,
    retry: false,
  });
  const [isReportSheetOpen, setIsReportSheetOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isCheckingRedirect, setIsCheckingRedirect] = useState(true);

  useEffect(() => {
    let isCancelled = false;

    const redirectIfNeeded = async () => {
      const shouldRedirect =
        authBridge.isAuthenticated() &&
        window.sessionStorage.getItem(REDIRECT_SESSION_KEY) === "true";

      if (!shouldRedirect) {
        if (!isCancelled) {
          setIsCheckingRedirect(false);
        }
        return;
      }

      const profileResponse = profile ?? (await refetch()).data;
      const nextPath = localizePath(getSubmitPath(profileResponse), locale);
      window.sessionStorage.removeItem(REDIRECT_SESSION_KEY);

      if (!isCancelled) {
        router.replace(nextPath);
      }
    };

    void redirectIfNeeded();

    return () => {
      isCancelled = true;
    };
  }, [locale, profile, refetch, router]);

  const handleSubmit = async () => {
    if (isSubmitting) {
      return;
    }

    setIsSubmitting(true);

    try {
      if (!authBridge.isAuthenticated()) {
        const token = await authBridge.ensureToken();
        if (!token) {
          return;
        }
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isCheckingRedirect) {
    return null;
  }

  return (
    <div className="pt-7">
      {isReportSheetOpen && (
        <ReportActionsSheet onClose={() => setIsReportSheetOpen(false)} />
      )}
      <header className="flex items-center justify-between">
        <NavigationButton icon="back" />
        <h1 className="font-faminela">{t.common.appName}</h1>
        <NavigationButton
          icon="support"
          iconLabel={t.common.support}
          onClick={() => setIsReportSheetOpen(true)}
        />
      </header>
      <main>
        <div className="flex flex-col items-center mt-16">
          <Image
            src={"/assets/images/Group 1597880466.svg"}
            alt={t.intro.imageAlt}
            width={168}
            height={155}
          />
          <h2 className="text-[#475569] font-bold mt-5 text-center">
            {t.intro.title}
          </h2>
          <p className=" text-center mt-2 text-xs text-[#4D4D4D]">
            {t.intro.description}
          </p>
        </div>
        <div className="flex items-center justify-between mt-4">
          <div className="flex items-center gap-0.5 p-2 border border-[#FD6ABB]/10 rounded-2xl">
            <Image
              src={"/assets/images/tabler_user-filled.svg"}
              alt="User"
              width={37}
              height={37}
            />
            <div className="flex flex-col items-start justify-start -mb-2">
              <p className="text-[#36363C] text-lg font-bold leading-3">120</p>
              <p className="text-[#36363C] text-[10px] font-semibold">
                {t.intro.userProfile}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-0.5 p-2 border border-[#FD6ABB]/10 rounded-2xl">
            <Image
              src={"/assets/images/icon-park-solid_success.svg"}
              alt="User"
              width={37}
              height={37}
            />
            <div className="flex flex-col items-start justify-start -mb-2">
              <p className="text-[#36363C] text-lg font-bold leading-3">14</p>
              <p className="text-[#36363C] text-[10px] font-semibold">
                {t.intro.matches}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-0.5 p-2 border border-[#FD6ABB]/10 rounded-2xl">
            <Image
              src={"/assets/images/typcn_heart-full-outline.svg"}
              alt="User"
              width={37}
              height={37}
            />
            <div className="flex flex-col items-start justify-start -mb-2">
              <p className="text-[#36363C] text-lg font-bold leading-3">14</p>
              <p className="text-[#36363C] text-[10px] font-semibold">
                {t.intro.marriage}
              </p>
            </div>
          </div>
        </div>
        <div className="mt-14 relative">
          <Image
            src={"/assets/images/Frame 2095586523.png"}
            alt={t.intro.videoAlt}
            width={344}
            height={221}
          />
          <Image
            src={"/assets/images/Frame 1116607280.svg"}
            alt={t.intro.playAlt}
            width={68}
            height={68}
            className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
          />
        </div>
        <div className="mt-7 pb-5">
          <Button onClick={handleSubmit} disabled={isSubmitting}>
            {t.common.submit}
          </Button>
        </div>
      </main>
    </div>
  );
}
