"use client"
import React, { type JSX, Suspense, useState } from "react"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { useSearchParams } from "next/navigation"

interface FormData {
  email: { value: string }
}

function WaitList(): JSX.Element {
  const searchParams = useSearchParams()
  const [email, setEmail] = useState("")
  const [collectionSuccess, setCollectionSuccess] = useState(false)
  const userid = searchParams?.get("userid")
  const username = searchParams?.get("username")

  console.log("userid", userid)
  async function onSubmit(event: React.SyntheticEvent): Promise<void> {
    event.preventDefault()
    const { email } = event.target as typeof event.target & FormData
    const emailAddress: string = email.value
    try {
      // Currently calls an unathenticated endpoint, in the future if we call cfapi we'll need an API key or m2m token or something else
      const response = await fetch("/cfapi/collect-email", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email: emailAddress, userId: userid, username }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      // Handle the response from the server
      console.log("Email collected successfully!")
      setCollectionSuccess(true)
    } catch (error) {
      console.error("Failed to collect email:", error)
    }
  }
  return (
    <div className="h-screen flex flex-col items-center justify-center">
      <h3 className="my-3 scroll-m-20 text-2xl font-semibold tracking-tight">
        You&apos;re on the waitlist! 💃
      </h3>
      Codeflash is currently in private beta. We will notify you when you can start using Codeflash
      if you enter your email below.
      {!collectionSuccess ? (
        /* eslint-disable-next-line @typescript-eslint/no-misused-promises */
        <form onSubmit={onSubmit} className="my-8" method="post">
          <div className="grid gap-2">
            <div className="grid gap-1">
              <Label className="sr-only" htmlFor="email">
                Email
              </Label>
              <Input
                value={email}
                onChange={(e) => {
                  setEmail(e.target.value)
                }}
                id="email"
                placeholder="name@example.com"
                type="email"
                autoCapitalize="none"
                autoComplete="email"
                autoCorrect="off"
              />
            </div>
            <Button>
              <span>Get Notified</span>
            </Button>
          </div>
        </form>
      ) : (
        <p className="text-green-500">Email collected successfully! We will reach out to you.</p>
      )}
    </div>
  )
}

export default function WaitlistPage(): JSX.Element {
  return (
    <Suspense>
      <WaitList />
    </Suspense>
  )
}
