import { query } from "@/lib/db"
import { redirect } from "next/navigation"

interface Props {
  params: Promise<{ token: string }>
}

function ErrorPage({ message }: { message: string }) {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-[#C84B4B]/10 to-[#C84B4B]/10 p-4">
      <div className="bg-white dark:bg-[#141414] rounded-2xl p-8 w-full max-w-md border border-[#D4D8CC] dark:border-[#CC0000]/20 shadow-lg text-center">
        <h1 className="text-2xl font-bold text-[#2D3020] dark:text-white mb-3">
          {message}
        </h1>
      </div>
    </div>
  )
}

export default async function JoinPage({ params }: Props) {
  const { token } = await params

  const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

  if (UUID_REGEX.test(token)) {
    redirect(`/call/${token}`)
  }

  const result = await query(
    `SELECT phone, created_at, expires_at FROM invites WHERE token = $1 LIMIT 1`,
    [token],
  )

  if (result.rows.length === 0) {
    return <ErrorPage message="This call link is invalid." />
  }

  const invite = result.rows[0]

  if (new Date(invite.expires_at) <= new Date()) {
    return <ErrorPage message="This call has expired." />
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-[#C84B4B]/10 to-[#C84B4B]/10 p-4">
      <div className="bg-white dark:bg-[#141414] rounded-2xl p-8 w-full max-w-md border border-[#D4D8CC] dark:border-[#CC0000]/20 shadow-lg text-center">
        <h1 className="text-2xl font-bold text-[#2D3020] dark:text-white mb-3">
          You&apos;re Invited!
        </h1>
        <p className="text-[#8A9078] text-sm mb-6">
          Someone wants to connect with you on our platform.
        </p>
        <div className="bg-[#FAFAF6] dark:bg-[#1A1A1A] rounded-xl p-4 mb-6 text-left">
          <p className="text-xs text-[#8A9078] mb-1">Contact Number</p>
          <p className="text-sm font-medium text-[#2D3020] dark:text-white">{invite.phone}</p>
        </div>
        <p className="text-xs text-[#8A9078] mb-6">
          Create an account to start making free voice calls to this person and others on the platform.
        </p>
        <a
          href="/register"
          className="block w-full bg-[#C84B4B] hover:bg-[#C84B4B]/80 dark:bg-[#FF1111] dark:hover:bg-[#CC0000] text-white font-semibold text-sm rounded-xl py-3 transition-all duration-200"
        >
          Create Account
        </a>
      </div>
    </div>
  )
}
