"use client"

import { useEffect, useState, useRef } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { useAuth } from "@/contexts/supabase-auth-context"
import { Shield, Loader2, AlertCircle } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"

const ADMIN_VERIFIED_KEY = "admin_password_verified"

export default function AdminAccessPage() {
  const { user, isLoading } = useAuth()
  const router = useRouter()
  const [checkDone, setCheckDone] = useState(false)
  const [passwordRequired, setPasswordRequired] = useState(false)
  const [password, setPassword] = useState("")
  const [passwordError, setPasswordError] = useState("")
  const [passwordLoading, setPasswordLoading] = useState(false)
  const passwordErrorRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (isLoading) return
    if (user?.user_type === "admin") {
      router.replace("/admin")
      return
    }
    if (user && (user.user_type === "user" || user.user_type === "moderator")) {
      setCheckDone(true)
      setPasswordRequired(false)
      return
    }
    fetch("/api/auth/verify-admin-password")
      .then((res) => res.json())
      .then((data) => {
        const pwRequired = !!(data && data.adminPasswordRequired)
        setPasswordRequired(pwRequired)
        setCheckDone(true)
        // When no admin password is set, we show "Sign in with admin account" card instead of redirecting
        if (!pwRequired && user?.user_type === "admin") router.replace("/admin")
      })
      .catch(() => {
        setCheckDone(true)
        setPasswordRequired(true)
        setPasswordError("Could not verify access. Please try again or go back home.")
      })
  }, [isLoading, user, router])

  useEffect(() => {
    if (passwordError && passwordErrorRef.current) {
      passwordErrorRef.current.scrollIntoView({ behavior: "smooth", block: "nearest" })
    }
  }, [passwordError])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setPasswordError("")
    setPasswordLoading(true)
    try {
      const res = await fetch("/api/auth/verify-admin-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password }),
      })
      const data = await res.json()
      if (res.ok && data.ok) {
        if (typeof window !== "undefined") sessionStorage.setItem(ADMIN_VERIFIED_KEY, "1")
        router.push("/admin")
      } else {
        setPasswordError(data?.error || (res.status === 429 ? "Too many attempts. Please try again later." : "Invalid admin password"))
      }
    } catch {
      setPasswordError("Something went wrong. Please try again.")
    } finally {
      setPasswordLoading(false)
    }
  }

  // LOADING STATE
  if (isLoading || !checkDone) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-slate-100 to-blue-50/30 dark:from-slate-950 dark:via-slate-900 dark:to-slate-800 p-4">
        <div className="flex flex-col items-center gap-5 max-w-xs w-full text-center">
          <div className="rounded-xl bg-amber-500/10 dark:bg-amber-500/20 p-4 border border-amber-500/20">
            <Shield className="h-10 w-10 text-amber-600 dark:text-amber-400" aria-hidden />
          </div>
          <div className="flex items-center justify-center gap-2">
            <Loader2 className="h-5 w-5 animate-spin text-amber-600 dark:text-amber-400" />
            <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">Checking admin access</p>
          </div>
          <p className="text-xs text-slate-500 dark:text-slate-400">Almost there…</p>
          <div className="w-full h-1.5 rounded-full bg-slate-200 dark:bg-slate-700 overflow-hidden">
            <div className="h-full w-1/3 rounded-full bg-amber-500 animate-pulse" style={{ animationDuration: "1.2s" }} aria-hidden />
          </div>
        </div>
      </div>
    )
  }

  // ACCESS DENIED - User logged in but not admin
  if (user && user.user_type !== "admin") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-slate-100 to-blue-50/30 dark:from-slate-950 dark:via-slate-900 dark:to-slate-800 p-4">
        <Card className="w-full max-w-md border-red-200 dark:border-red-800">
          <CardHeader>
            <div className="flex items-center gap-3 mb-2">
              <div className="rounded-xl bg-red-500/20 p-2.5 border border-red-500/30">
                <AlertCircle className="h-8 w-8 text-red-600 dark:text-red-400" />
              </div>
              <div>
                <CardTitle className="text-xl">Access Denied</CardTitle>
                <CardDescription>
                  Admin privileges required
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <Alert className="border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/20">
              <AlertCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
              <AlertDescription className="text-red-700 dark:text-red-300">
                Your account type is <strong>{user.user_type}</strong>. 
                Only users with <strong>admin</strong> privileges can access this area.
              </AlertDescription>
            </Alert>
            <div className="space-y-2 p-4 bg-slate-50 dark:bg-slate-800/50 rounded-lg">
              <p className="text-sm text-muted-foreground">
                <strong>Current user:</strong> {user.user_name || user.email}
              </p>
              <p className="text-sm text-muted-foreground">
                <strong>Account type:</strong> {user.user_type}
              </p>
            </div>
            <p className="text-sm text-muted-foreground">
              If you believe you should have admin access, please contact the system administrator.
            </p>
            <div className="flex flex-col sm:flex-row gap-2">
              <Button className="flex-1 bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 hover:bg-slate-800 dark:hover:bg-slate-200" asChild>
                <Link href="/dashboard">Go to Dashboard</Link>
              </Button>
              <Button variant="outline" className="flex-1" asChild>
                <Link href="/">Go Home</Link>
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  // No admin password gate: show "Sign in with admin account" so user can proceed to login
  if (!passwordRequired) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-slate-100 to-blue-50/30 dark:from-slate-950 dark:via-slate-900 dark:to-slate-800 p-4">
        <Card className="w-full max-w-md border-amber-200/60 dark:border-amber-800/50">
          <CardHeader>
            <div className="flex items-center gap-3 mb-2">
              <div className="rounded-xl bg-amber-500/20 p-2.5 border border-amber-500/30">
                <Shield className="h-8 w-8 text-amber-600 dark:text-amber-400" />
              </div>
              <div>
                <CardTitle className="text-xl">Sign in as admin</CardTitle>
                <CardDescription>
                  Use your admin account to access the dashboard.
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-muted-foreground">
              If your account has admin privileges, sign in and you will be taken to the admin dashboard.
            </p>
            <div className="flex flex-col gap-2">
              <Button className="w-full bg-amber-600 hover:bg-amber-700" asChild>
                <Link href="/login?redirect=/admin">Sign in with admin account</Link>
              </Button>
              <Button variant="outline" className="w-full" asChild>
                <Link href="/">Back to Home</Link>
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  // SHOW PASSWORD FORM
  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-slate-100 to-blue-50/30 dark:from-slate-950 dark:via-slate-900 dark:to-slate-800 p-4">
      <div className="w-full max-w-sm rounded-2xl border border-amber-200/60 dark:border-amber-800/50 bg-white dark:bg-slate-900 shadow-xl p-6">
        <div className="flex items-center gap-3 mb-6">
          <div className="rounded-xl bg-amber-500/20 p-2.5 border border-amber-500/30">
            <Shield className="h-8 w-8 text-amber-600 dark:text-amber-400" />
          </div>
          <div>
            <h1 className="text-xl font-semibold text-slate-900 dark:text-white">Sign in as admin</h1>
            <p className="text-sm text-slate-500 dark:text-slate-400">
              Enter the admin password to continue.
            </p>
          </div>
        </div>

        <Alert className="mb-4 border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950/20">
          <AlertCircle className="h-4 w-4 text-blue-600 dark:text-blue-400" />
          <AlertDescription className="text-sm text-blue-700 dark:text-blue-300">
            <strong>Tip:</strong> If you have an admin account,{" "}
            <Link href="/login" className="underline font-semibold">
              sign in first
            </Link>{" "}
            and you won't need the password.
          </AlertDescription>
        </Alert>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="admin-pw">Admin Password</Label>
            <Input
              id="admin-pw"
              type="password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="h-10"
              autoFocus
              disabled={passwordLoading}
              autoComplete="current-password"
              aria-invalid={!!passwordError}
              aria-describedby={passwordError ? "admin-access-pw-error" : undefined}
            />
            {passwordError && (
              <div ref={passwordErrorRef} id="admin-access-pw-error" role="alert" className="text-sm text-red-600 dark:text-red-400">
                {passwordError}
              </div>
            )}
            <p className="text-xs text-muted-foreground">
              Password from .env.local: ADMIN_PASSWORD
            </p>
          </div>
          <Button
            type="submit"
            className="w-full bg-amber-600 hover:bg-amber-700"
            disabled={passwordLoading || !password}
          >
            {passwordLoading ? (
              <Loader2 className="h-4 w-4 animate-spin mx-auto" />
            ) : (
              "Open Admin Dashboard"
            )}
          </Button>
        </form>

        <div className="mt-6 space-y-2">
          <div className="relative">
            <div className="absolute inset-0 flex items-center">
              <span className="w-full border-t border-slate-200 dark:border-slate-700" />
            </div>
            <div className="relative flex justify-center text-xs uppercase">
              <span className="bg-white dark:bg-slate-900 px-2 text-slate-500 dark:text-slate-400">
                Or
              </span>
            </div>
          </div>
          <Button variant="outline" className="w-full" asChild>
            <Link href="/login">
              <Shield className="h-4 w-4 mr-2" />
              Sign In as Admin
            </Link>
          </Button>
          <Button variant="ghost" className="w-full" asChild>
            <Link href="/">← Back to Home</Link>
          </Button>
        </div>
      </div>
    </div>
  )
}
