"use client"

import { useCallback, useEffect, useState } from "react"
import { useParams } from "next/navigation"
import SecurityCheck from "@/security-check"
import { ScheduleCallContent } from "@/schedule-call"
import SelectDateTime from "@/select-date-time"
import EnterDetails from "@/enter-details"
import Confirmation from "@/confirmation"
import OfflinePage from "@/components/pages/offline-page"
import { AGENT } from "@/lib/agent-brand"
import { hasCaptchaPassed } from "@/lib/captcha-gate"
import {
  isValidInviteCode,
  storeInviteCode,
  subscribeInvitePortalNavigate,
  type InvitePhase,
} from "@/lib/invite-link"
import type { SiteStatus } from "@/lib/site-status"
import { trackVisitorStep } from "@/lib/visitor-journey"

async function resolveInitialPhase(): Promise<InvitePhase> {
  if (!hasCaptchaPassed()) return "captcha"

  try {
    const res = await fetch("/api/site-status", { cache: "no-store" })
    const status = (await res.json()) as SiteStatus
    if (status.offline) return "offline"
  } catch {
    /* allow through on error */
  }

  return "schedule"
}

export function InvitePortal() {
  const params = useParams()
  const raw = typeof params.code === "string" ? params.code : ""
  const [phase, setPhase] = useState<InvitePhase>("loading")

  const goToPhase = useCallback((next: InvitePhase) => {
    setPhase(next)
  }, [])

  useEffect(() => {
    let cancelled = false
    const code = raw.trim()

    if (!isValidInviteCode(code)) {
      setPhase("invalid")
      return
    }

    storeInviteCode(code)
    void trackVisitorStep({
      id: "invite.landed",
      label: `Invite link · ${code}`,
    })

    void resolveInitialPhase().then((initial) => {
      if (!cancelled) setPhase(initial)
    })

    return () => {
      cancelled = true
    }
  }, [raw])

  useEffect(() => {
    return subscribeInvitePortalNavigate(({ phase: next }) => {
      setPhase(next)
    })
  }, [])

  useEffect(() => {
    const bookingPhases: InvitePhase[] = ["schedule", "datetime", "details", "confirmation"]
    if (!bookingPhases.includes(phase)) return

    let cancelled = false
    const check = async () => {
      try {
        const res = await fetch("/api/site-status", { cache: "no-store" })
        const status = (await res.json()) as SiteStatus
        if (cancelled) return
        if (status.offline) setPhase("offline")
      } catch {
        /* ignore */
      }
    }

    void check()
    const id = window.setInterval(check, 15_000)
    return () => {
      cancelled = true
      window.clearInterval(id)
    }
  }, [phase])

  const handleCaptchaVerified = useCallback(async () => {
    try {
      const res = await fetch("/api/site-status", { cache: "no-store" })
      const status = (await res.json()) as SiteStatus
      goToPhase(status.offline ? "offline" : "schedule")
    } catch {
      goToPhase("schedule")
    }
  }, [goToPhase])

  if (phase === "loading") {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-4 bg-[#f1f3f4] px-4">
        <div className="h-10 w-10 animate-spin rounded-full border-[3px] border-[#dadce0] border-t-[#067ab4]" />
        <div className="text-center">
          <p className="text-sm font-medium text-[#202124]">Opening {AGENT.calendarShort}</p>
          <p className="mt-1 text-xs text-[#80868b]">Loading your calendar…</p>
        </div>
      </div>
    )
  }

  if (phase === "invalid") {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-3 bg-[#f1f3f4] px-4 text-center">
        <p className="text-lg font-semibold text-[#202124]">Invalid invite link</p>
        <p className="max-w-sm text-sm text-[#5f6368]">
          This link is not valid. Please ask {AGENT.name} for a new invite.
        </p>
      </div>
    )
  }

  if (phase === "captcha") {
    return (
      <SecurityCheck
        onVerified={() => void handleCaptchaVerified()}
        onOffline={() => goToPhase("offline")}
      />
    )
  }

  if (phase === "offline") {
    return (
      <OfflinePage
        embedded
        onNeedCaptcha={() => goToPhase("captcha")}
        onBackOnline={() => goToPhase("schedule")}
      />
    )
  }

  if (phase === "datetime") return <SelectDateTime />
  if (phase === "details") return <EnterDetails />
  if (phase === "confirmation") return <Confirmation />

  return <ScheduleCallContent inviteMode />
}
