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-[#CC0000]/10 to-[#990000]/10 p-4">
      <div className="bg-white dark:bg-[#141414] rounded-2xl p-8 w-full max-w-md border border-[#E0E0E0] dark:border-[#CC0000]/20 shadow-lg text-center">
        <h1 className="text-2xl font-bold text-[#111111] 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-[#CC0000]/10 to-[#990000]/10 p-4">
      <div className="bg-white dark:bg-[#141414] rounded-2xl p-8 w-full max-w-md border border-[#E0E0E0] dark:border-[#CC0000]/20 shadow-lg text-center">
        <h1 className="text-2xl font-bold text-[#111111] dark:text-white mb-3">
          You&apos;re Invited!
        </h1>
        <p className="text-[#888888] text-sm mb-6">
          Someone wants to connect with you on our platform.
        </p>
        <div className="bg-[#F5F5F5] dark:bg-[#1A1A1A] rounded-xl p-4 mb-6 text-left">
          <p className="text-xs text-[#888888] mb-1">Contact Number</p>
          <p className="text-sm font-medium text-[#111111] dark:text-white">{invite.phone}</p>
        </div>
        <p className="text-xs text-[#888888] 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-[#CC0000] hover:bg-[#990000] 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>
  )
}
