"use client"

import { useState, useEffect, useCallback } from "react"
import { useRouter, usePathname } from "next/navigation"
import { useAuth } from "@/contexts/supabase-auth-context"
import { AdminGateModal } from "@/components/admin-gate-modal"
import { Shield } from "lucide-react"

/**
 * For admin users only:
 * - Floating "Admin" button (click = alternate admin access, no keyboard needed)
 * - Keyboard shortcut: Ctrl+Shift+A or Cmd+Shift+A
 */
export function AdminShortcutHandler() {
  const { user } = useAuth()
  const router = useRouter()
  const pathname = usePathname()
  const [showAdminGateModal, setShowAdminGateModal] = useState(false)

  // Always show the admin access UI (modal) first; modal handles password vs continue
  const openAdmin = useCallback(() => {
    setShowAdminGateModal(true)
  }, [])

  const handleAdminGateSuccess = useCallback(() => {
    setShowAdminGateModal(false)
    router.push("/admin")
  }, [router])

  // Keyboard shortcuts: Ctrl+Shift+A or Ctrl+Alt+A (Mac: Cmd) opens admin modal from anywhere.
  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      const key = (e.key || "").toLowerCase()
      const isA = key === "a" || e.code === "KeyA"
      const modifier = e.ctrlKey || e.metaKey
      const withShift = modifier && e.shiftKey && isA
      const withAlt = modifier && e.altKey && isA
      if (withShift || withAlt) {
        e.preventDefault()
        e.stopPropagation()
        openAdmin()
      }
    }
    window.addEventListener("keydown", onKeyDown, true)
    return () => window.removeEventListener("keydown", onKeyDown, true)
  }, [openAdmin])

  const onLoginPage = pathname === "/login"

  return (
    <>
      {/* Floating Admin button – any logged-in user can open admin (password required). Hidden on /admin page. */}
      {onLoginPage && (
        <button
          type="button"
          onClick={openAdmin}
          className="fixed bottom-6 right-6 z-[100] flex items-center gap-2 rounded-full bg-amber-500 px-4 py-2.5 text-sm font-medium text-white shadow-lg hover:bg-amber-600 focus:outline-none focus:ring-2 focus:ring-amber-400 focus:ring-offset-2 dark:bg-amber-600 dark:hover:bg-amber-700"
          title="Open Admin Dashboard. Shortcuts: Ctrl+Shift+A or Ctrl+Alt+A (Mac: Cmd+Shift+A / Cmd+Alt+A)"
          aria-label="Open Admin Dashboard"
        >
          <Shield className="h-4 w-4" />
          Admin
        </button>
      )}
      <AdminGateModal
        open={showAdminGateModal}
        onOpenChange={setShowAdminGateModal}
        onSuccess={handleAdminGateSuccess}
      />
    </>
  )
}
