import Link from "next/link"
import { redirect } from "next/navigation"
import { getSessionUser } from "@/lib/session"
import { acceptInvite } from "@/app/actions/team"
import { Logo } from "@/components/shared/logo"
import { XCircle } from "lucide-react"

export const metadata = { title: "Accept Team Invite" }

export default async function AcceptInvitePage({
  params,
}: {
  params: Promise<{ token: string }>
}) {
  const { token } = await params

  // Require login. Bounce through /login with a next param so the user lands
  // back here (and the invite is accepted) after signing in.
  const user = await getSessionUser()
  if (!user) {
    const next = encodeURIComponent(`/team/accept/${token}`)
    redirect(`/login?next=${next}`)
  }

  const result = await acceptInvite(token)

  // On success, drop them straight into the dashboard operating under the
  // owner's account.
  if (result.ok) redirect("/dashboard")

  return (
    <div className="flex min-h-screen items-center justify-center bg-[#09090b] px-4">
      <div className="w-full max-w-md">
        <div className="mb-8 flex flex-col items-center">
          <Logo size="lg" />
        </div>
        <div className="rounded-xl border border-white/10 bg-[#111118] p-8 text-center">
          <div className="mx-auto mb-4 w-fit rounded-xl bg-red-500/10 p-3">
            <XCircle className="h-6 w-6 text-red-400" />
          </div>
          <h1 className="text-lg font-semibold text-white">Can&apos;t accept this invite</h1>
          <p className="mx-auto mt-2 max-w-sm text-sm text-white/50">{result.error}</p>
          <Link
            href="/dashboard"
            className="mt-6 inline-flex items-center justify-center rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-500"
          >
            Go to dashboard
          </Link>
        </div>
      </div>
    </div>
  )
}
