"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { JefflixLogo } from "@/components/jefflix-logo"

export default function GatePage() {
  const [code, setCode] = useState("")
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)
  const router = useRouter()

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError("")
    setLoading(true)

    const res = await fetch("/api/verify-code", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ code }),
    })

    if (res.ok) {
      router.push("/")
      router.refresh()
    } else {
      setError("Wrong code. Try again.")
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-background flex items-center justify-center">
      <div className="absolute inset-0 bg-gradient-to-br from-yellow-50/80 via-background/90 to-green-50/80" />
      <div className="relative w-full max-w-md mx-auto px-4">
        <div className="text-center space-y-8">
          <JefflixLogo />
          <p className="text-lg text-muted-foreground">
            Enter the access code to continue
          </p>
          <form onSubmit={handleSubmit} className="space-y-4">
            <input
              type="text"
              inputMode="numeric"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              placeholder="Access code"
              autoFocus
              className="w-full text-center text-2xl tracking-widest px-4 py-3 rounded-lg border-2 border-border bg-card focus:outline-none focus:ring-2 focus:ring-ring"
            />
            {error && (
              <p className="text-destructive font-medium">{error}</p>
            )}
            <button
              type="submit"
              disabled={loading || !code}
              className="w-full py-3 px-6 rounded-lg bg-primary text-primary-foreground font-bold text-lg hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              {loading ? "Checking..." : "Enter"}
            </button>
          </form>
        </div>
      </div>
    </div>
  )
}
