"use client"

import type React from "react"
import Image from "next/image"
import { useState } from "react"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { ArrowLeft, Shield, Key, CreditCard, HelpCircle } from "lucide-react"
import { useRouter } from "next/navigation"
import { toast } from "@/lib/toast"
import { LoadingSpinner } from "@/components/loading-spinner"

export default function LoginPage() {
  const [serialNumber, setSerialNumber] = useState("")
  const [pin, setPin] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [errors, setErrors] = useState<{ serialNumber?: string; pin?: string; general?: string }>({})
  const router = useRouter()

  const validateForm = () => {
    const newErrors: typeof errors = {}

    if (!serialNumber.trim()) {
      newErrors.serialNumber = "Serial number is required"
    }

    if (!pin.trim()) {
      newErrors.pin = "PIN is required"
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!validateForm()) {
      toast.error("Please fill in all required fields")
      return
    }

    setIsLoading(true)
    setErrors({})

    try {
      const response = await fetch("/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ serialNumber: serialNumber.trim(), pin: pin.trim() }),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || "Login failed")
      }

      toast.success("Login successful! Redirecting to dashboard...")
      router.push("/dashboard")
    } catch (error) {
      console.error("[v0] Login error:", error)
      const errorMessage = error instanceof Error ? error.message : "An unexpected error occurred"
      setErrors({ general: errorMessage })
      toast.error(errorMessage)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-background flex items-center justify-center p-4 relative overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-br from-accent/5 via-transparent to-accent/10"></div>
      <div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_50%,rgba(120,119,198,0.1),transparent_50%)]"></div>

      <div className="w-full max-w-md space-y-8 relative z-10 animate-fade-in">
        <div className="text-center space-y-6">
          <Link
            href="/"
            className="inline-flex items-center gap-2 text-muted-foreground hover:text-foreground transition-all duration-200 hover:gap-3 group"
            aria-label="Back to home page"
          >
            <ArrowLeft className="h-4 w-4 transition-transform group-hover:-translate-x-1" />
            <span className="text-sm font-medium">Back to Home</span>
          </Link>

          <div className="space-y-4">
            <div className="flex items-center justify-center gap-3">
              <div className="p-2 bg-accent/10 rounded-xl">
                <Image
                  src="/images/fanaka-logo.png"
                  alt="Fanaka International University College Logo"
                  width={32}
                  height={32}
                  className="h-8 w-auto"
                />
              </div>
              <div className="text-center">
                <span className="text-xl font-black text-foreground tracking-tight block leading-tight">
                  Fanaka International
                </span>
                <span className="text-lg font-black text-foreground tracking-tight block leading-tight">
                  University College
                </span>
              </div>
            </div>
            <div className="space-y-2">
              <h1 className="text-3xl font-bold text-foreground tracking-tight">Welcome Back</h1>
              <p className="text-muted-foreground text-lg">
                Enter your voucher credentials to access your application portal
              </p>
            </div>
          </div>
        </div>

        <Card className="border-border/50 bg-card/50 backdrop-blur-sm shadow-2xl">
          <CardHeader className="space-y-3 pb-6">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-accent/10 rounded-lg">
                <Shield className="h-5 w-5 text-accent" />
              </div>
              <div>
                <CardTitle className="text-xl text-foreground">Secure Login</CardTitle>
                <CardDescription className="text-base text-muted-foreground">
                  Use your voucher credentials to continue
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            <form onSubmit={handleSubmit} className="space-y-6" noValidate>
              {errors.general && (
                <div
                  className="p-4 bg-destructive/10 border border-destructive/20 rounded-lg animate-slide-in"
                  role="alert"
                >
                  <p className="text-sm text-destructive font-medium">{errors.general}</p>
                </div>
              )}

              <div className="space-y-3">
                <Label htmlFor="serial" className="text-sm font-medium text-foreground flex items-center gap-2">
                  <Key className="h-4 w-4 text-muted-foreground" />
                  Voucher Serial Number
                  <span className="text-destructive ml-1" aria-label="required">
                    *
                  </span>
                </Label>
                <Input
                  id="serial"
                  type="text"
                  placeholder="Enter your voucher serial number"
                  value={serialNumber}
                  onChange={(e) => {
                    setSerialNumber(e.target.value)
                    if (errors.serialNumber) {
                      setErrors((prev) => ({ ...prev, serialNumber: undefined }))
                    }
                  }}
                  required
                  aria-invalid={errors.serialNumber ? "true" : "false"}
                  aria-describedby={errors.serialNumber ? "serial-error" : undefined}
                  className={`bg-input border-border/50 focus:border-accent transition-all duration-200 ${
                    errors.serialNumber ? "border-destructive focus:border-destructive" : ""
                  }`}
                />
                {errors.serialNumber && (
                  <p id="serial-error" className="text-sm text-destructive animate-slide-in" role="alert">
                    {errors.serialNumber}
                  </p>
                )}
              </div>

              <div className="space-y-3">
                <Label htmlFor="pin" className="text-sm font-medium text-foreground flex items-center gap-2">
                  <Shield className="h-4 w-4 text-muted-foreground" />
                  Voucher PIN
                  <span className="text-destructive ml-1" aria-label="required">
                    *
                  </span>
                </Label>
                <Input
                  id="pin"
                  type="password"
                  placeholder="Enter your voucher PIN"
                  value={pin}
                  onChange={(e) => {
                    setPin(e.target.value)
                    if (errors.pin) {
                      setErrors((prev) => ({ ...prev, pin: undefined }))
                    }
                  }}
                  required
                  aria-invalid={errors.pin ? "true" : "false"}
                  aria-describedby={errors.pin ? "pin-error" : undefined}
                  className={`bg-input border-border/50 focus:border-accent transition-all duration-200 ${
                    errors.pin ? "border-destructive focus:border-destructive" : ""
                  }`}
                />
                {errors.pin && (
                  <p id="pin-error" className="text-sm text-destructive animate-slide-in" role="alert">
                    {errors.pin}
                  </p>
                )}
              </div>

              <Button
                type="submit"
                className="w-full bg-accent hover:bg-accent/90 text-accent-foreground font-medium py-3 transition-all duration-200 hover:shadow-lg hover:shadow-accent/25"
                disabled={isLoading}
                aria-describedby={isLoading ? "login-status" : undefined}
              >
                {isLoading ? (
                  <>
                    <LoadingSpinner size="sm" className="mr-2" />
                    Authenticating...
                  </>
                ) : (
                  <>
                    <Shield className="h-4 w-4 mr-2" />
                    Access Portal
                  </>
                )}
              </Button>
              {isLoading && (
                <p id="login-status" className="sr-only">
                  Processing login request, please wait
                </p>
              )}
            </form>
          </CardContent>
        </Card>

        <Card className="border-border/50 bg-card/30 backdrop-blur-sm">
          <CardContent className="pt-6">
            <div className="text-center space-y-4">
              <div className="flex items-center justify-center gap-2">
                <HelpCircle className="h-5 w-5 text-muted-foreground" />
                <h3 className="font-semibold text-foreground">Need a Voucher?</h3>
              </div>
              <p className="text-sm text-muted-foreground leading-relaxed">
                If you haven't purchased a voucher yet, you can get one using our secure payment system to start your
                application process.
              </p>
              <Button
                asChild
                variant="outline"
                className="w-full bg-transparent border-border/50 hover:bg-accent/10 hover:border-accent/50 transition-all duration-200"
              >
                <Link href="/purchase-voucher" className="flex items-center gap-2">
                  <CreditCard className="h-4 w-4" />
                  Purchase Voucher
                </Link>
              </Button>
            </div>
          </CardContent>
        </Card>

        <div className="text-center">
          <p className="text-sm text-muted-foreground">
            Having trouble logging in?{" "}
            <Link
              href="#"
              className="text-accent hover:text-accent/80 font-medium transition-colors duration-200 hover:underline"
            >
              Contact Support
            </Link>
          </p>
        </div>
      </div>
    </div>
  )
}
