"use client";

import { useAuth } from "@/contexts/supabase-auth-context";
import { useRouter, usePathname } from "next/navigation";
import { useEffect, useState, useRef } from "react";
import { Shield, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const ADMIN_VERIFIED_KEY = "admin_password_verified";

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [checkDone, setCheckDone] = useState(false);
  const [passwordRequired, setPasswordRequired] = useState(false);
  const [showPasswordForm, setShowPasswordForm] = useState(false);
  const [password, setPassword] = useState("");
  const [passwordError, setPasswordError] = useState("");
  const [passwordLoading, setPasswordLoading] = useState(false);
  const passwordErrorRef = useRef<HTMLDivElement>(null);

  // Check: admin password required? If yes, no login needed—just password. If no, require logged-in admin.
  useEffect(() => {
    if (isLoading) return;

    const goLogin = () => {
      router.replace(`/login?redirect=${encodeURIComponent(pathname || "/admin")}`);
    };
    const goDashboard = () => {
      router.replace("/dashboard");
    };

    fetch("/api/auth/verify-admin-password")
      .then((res) => res.json())
      .then((data) => {
        const needPassword = !!data?.adminPasswordRequired;
        setPasswordRequired(needPassword);
        const verified = typeof window !== "undefined" && sessionStorage.getItem(ADMIN_VERIFIED_KEY) === "1";

        if (needPassword) {
          if (verified) {
            setShowPasswordForm(false);
          } else {
            setShowPasswordForm(true);
          }
          setCheckDone(true);
        } else {
          if (!user) {
            goLogin();
            return;
          }
          if (user.user_type !== "admin") {
            goDashboard();
            return;
          }
          setCheckDone(true);
        }
      })
      .catch(() => {
        if (user?.user_type === "admin") {
          setCheckDone(true);
          setShowPasswordForm(false);
        } else {
          goDashboard();
        }
      });
  }, [user, isLoading, router, pathname]);

  const handlePasswordSubmit = 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");
        setShowPasswordForm(false);
        setPassword("");
      } else {
        setPasswordError(data?.error || "Invalid admin password");
      }
    } catch {
      setPasswordError("Something went wrong. Please try again.");
    } finally {
      setPasswordLoading(false);
    }
  };

  // Scroll error into view when password error is set
  useEffect(() => {
    if (passwordError && passwordErrorRef.current) {
      passwordErrorRef.current.scrollIntoView({ behavior: "smooth", block: "nearest" });
    }
  }, [passwordError]);

  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>
            <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">Checking admin access</p>
            <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">Almost there…</p>
          </div>
          <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>
    );
  }

  // Password required but not verified: show password form (no login required)
  if (passwordRequired && showPasswordForm) {
    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">Admin Dashboard</h1>
              <p className="text-sm text-slate-500 dark:text-slate-400">Enter the admin password to continue.</p>
            </div>
          </div>
          <form onSubmit={handlePasswordSubmit} 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-pw-error" : undefined}
              />
              {passwordError && (
                <div ref={passwordErrorRef} id="admin-pw-error" role="alert" className="text-sm text-red-600 dark:text-red-400">
                  {passwordError}
                </div>
              )}
            </div>
            <Button type="submit" className="w-full bg-amber-600 hover:bg-amber-700" disabled={passwordLoading}>
              {passwordLoading ? <Loader2 className="h-4 w-4 animate-spin mx-auto" /> : "Access Admin Dashboard"}
            </Button>
          </form>
          <Button variant="outline" className="w-full mt-2" onClick={() => router.push("/")}>
            Cancel
          </Button>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
