"use client";
import { useState } from "react";
import { useLocale } from "next-intl";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import InviteShell from "./InviteShell";
import InviteStepper from "./InviteStepper";
import WelcomeStep from "./WelcomeStep";
import RegisterStep from "./RegisterStep";
import SuccessStep from "./SuccessStep";
import InviteUnavailable from "./InviteUnavailable";
import { isInviteExpired, type InvitePayload } from "@/lib/invite";

type Step = "welcome" | "register" | "success";

const STEP_INDEX: Record<Step, number> = { welcome: 0, register: 1, success: 3 };

interface InviteFlowProps {
  invite: InvitePayload;
  dashboardUrl: string;
}

export default function InviteFlow({ invite, dashboardUrl }: InviteFlowProps) {
  const locale = useLocale();
  const isRTL = locale === "ar";
  const reduceMotion = useReducedMotion();
  const [step, setStep] = useState<Step>("welcome");
  const [email, setEmail] = useState("");
  const [expired, setExpired] = useState(false);

  const goTo = (next: Step) => {
    // The page may have been left open past the expiry date
    if (next !== "success" && isInviteExpired(invite.x)) {
      setExpired(true);
      return;
    }
    setStep(next);
    window.scrollTo({ top: 0, behavior: reduceMotion ? "auto" : "smooth" });
  };

  // Slide in the reading direction
  const offset = reduceMotion ? 0 : isRTL ? -24 : 24;

  if (expired) {
    return (
      <InviteUnavailable reason="expired" invite={invite} dashboardUrl={dashboardUrl} />
    );
  }

  return (
    <InviteShell>
      <InviteStepper current={STEP_INDEX[step]} />
      <AnimatePresence mode="wait" initial={false}>
        <motion.div
          key={step}
          initial={{ opacity: 0, x: offset }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: -offset }}
          transition={{ duration: 0.25, ease: "easeOut" }}
        >
          {step === "welcome" && (
            <WelcomeStep
              invite={invite}
              isRTL={isRTL}
              dashboardUrl={dashboardUrl}
              onAccept={() => goTo("register")}
            />
          )}
          {step === "register" && (
            <RegisterStep
              invite={invite}
              onExpired={() => setExpired(true)}
              onBack={() => goTo("welcome")}
              onSuccess={(data) => {
                setEmail(data.email);
                goTo("success");
              }}
            />
          )}
          {step === "success" && (
            <SuccessStep invite={invite} email={email} dashboardUrl={dashboardUrl} />
          )}
        </motion.div>
      </AnimatePresence>
    </InviteShell>
  );
}
