"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useAuth } from "@/contexts/supabase-auth-context";
import { Shield, Loader2, ArrowRight } from "lucide-react";

interface AdminGateModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

export function AdminGateModal({
  open,
  onOpenChange,
  onSuccess,
}: AdminGateModalProps) {
  const { user } = useAuth();
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [passwordRequired, setPasswordRequired] = useState<boolean | null>(
    null,
  );
  const isAdmin = user?.user_type === "admin";
  const passwordInputRef = useRef<HTMLInputElement>(null);

  // When modal opens, check if admin password is required
  useEffect(() => {
    if (!open) {
      setPasswordRequired(null);
      return;
    }
    let cancelled = false;
    fetch("/api/auth/verify-admin-password")
      .then((res) => res.json())
      .then((data) => {
        if (!cancelled) setPasswordRequired(!!data?.adminPasswordRequired);
      })
      .catch(() => {
        if (!cancelled) setPasswordRequired(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open]);

  // Hotkey: Escape to close modal
  useEffect(() => {
    if (!open) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onOpenChange(false);
        e.preventDefault();
      }
    };
    document.addEventListener("keydown", onKeyDown, true);
    return () => document.removeEventListener("keydown", onKeyDown, true);
  }, [open, onOpenChange]);

  useEffect(() => {
    if (open && passwordRequired === true && passwordInputRef.current) {
      const t = setTimeout(() => passwordInputRef.current?.focus(), 100);
      return () => clearTimeout(t);
    }
  }, [open, passwordRequired]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(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_password_verified", "1");
        setPassword("");
        onOpenChange(false);
        onSuccess();
        return;
      }
      setError(data?.error || "Invalid admin password");
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const handleContinueWithoutPassword = () => {
    onOpenChange(false);
    onSuccess();
  };

  const handleClose = (open: boolean) => {
    if (!open) {
      setPassword("");
      setError("");
    }
    onOpenChange(open);
  };

  const isLoadingGate = open && passwordRequired === null;

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[380px] rounded-xl p-6 gap-4 border-amber-200/60 dark:border-amber-800/50">
        <DialogHeader className="space-y-2">
          <div className="flex items-center gap-3">
            <div className="rounded-xl bg-amber-500/20 p-2.5 border border-amber-500/30">
              <Shield className="h-7 w-7 text-amber-600 dark:text-amber-400" />
            </div>
            <div>
              <DialogTitle className="text-xl">Sign in as admin</DialogTitle>
              <DialogDescription className="text-sm mt-0.5">
                Open the Admin Dashboard to manage users, builds, and activity.
              </DialogDescription>
            </div>
          </div>
        </DialogHeader>

        {isLoadingGate && (
          <div className="py-6 flex items-center justify-center">
            <Loader2 className="h-8 w-8 animate-spin text-amber-600" />
          </div>
        )}

        {!isLoadingGate && passwordRequired === true && (
          <div className="space-y-4">
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="admin-password">Admin password</Label>
                <Input
                  ref={passwordInputRef}
                  id="admin-password"
                  type="password"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="h-10"
                  autoFocus
                  autoComplete="current-password"
                  disabled={loading}
                />
                {error && (
                  <p className="text-xs text-red-600 dark:text-red-400">
                    {error}
                  </p>
                )}
              </div>
              <DialogFooter className="gap-2 sm:gap-0">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => handleClose(false)}
                  disabled={loading}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  size="sm"
                  disabled={loading}
                  className="bg-amber-600 hover:bg-amber-700"
                >
                  {loading ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    "Continue"
                  )}
                </Button>
              </DialogFooter>
            </form>
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <span className="w-full border-t border-border" />
              </div>
              <div className="relative flex justify-center text-xs uppercase">
                <span className="bg-background px-2 text-muted-foreground">
                  Or
                </span>
              </div>
            </div>
            <div className="flex justify-center">
              <Button variant="ghost" size="sm" className="text-amber-600 hover:text-amber-700 hover:bg-amber-500/10" asChild>
                <Link href="/login?redirect=/admin" onClick={() => handleClose(false)}>
                  Sign in with my admin account
                  <ArrowRight className="h-4 w-4 ml-1" />
                </Link>
              </Button>
            </div>
          </div>
        )}

        {!isLoadingGate && passwordRequired === false && (
          <DialogFooter className="gap-2 sm:gap-0 pt-2 flex-col sm:flex-row">
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => handleClose(false)}
            >
              Cancel
            </Button>
            {isAdmin ? (
              <Button
                type="button"
                size="sm"
                onClick={handleContinueWithoutPassword}
                className="bg-amber-600 hover:bg-amber-700"
              >
                Continue to Admin Dashboard
                <ArrowRight className="h-4 w-4 ml-2" />
              </Button>
            ) : (
              <Button
                size="sm"
                className="bg-amber-600 hover:bg-amber-700"
                asChild
              >
                <Link href="/login?redirect=/admin" onClick={() => handleClose(false)}>
                  Sign in with admin account
                  <ArrowRight className="h-4 w-4 ml-2" />
                </Link>
              </Button>
            )}
          </DialogFooter>
        )}
      </DialogContent>
    </Dialog>
  );
}
