"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { checkPassword, setAuthenticated } from "@/lib/auth"

export default function LoginPage() {
  const [password, setPassword] = 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 valid = await checkPassword(password)
    if (valid) {
      setAuthenticated(true)
      router.push("/videos")
    } else {
      setError("Incorrect password. Please try again.")
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center py-12 px-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl font-bold">Client Access</CardTitle>
          <CardDescription>
            Enter the password provided by Higgy to access video tutorials
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <Input
                id="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Enter your access password"
                required
              />
              {error && (
                <p className="text-sm text-red-500">{error}</p>
              )}
            </div>
            <Button
              type="submit"
              className="w-full bg-[#8BC34A] hover:bg-[#7CB342] text-white"
              disabled={loading}
            >
              {loading ? "Checking..." : "Access Videos"}
            </Button>
            <p className="text-center text-sm text-muted-foreground">
              Don&apos;t have a password?{" "}
              <Link
                href="/"
                className="text-[#8BC34A] hover:underline font-medium"
              >
                Contact Higgy
              </Link>
            </p>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
