"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import { Mail, Lock, Loader2, Shield, Eye, EyeOff, CheckCircle2, AlertCircle } from "lucide-react";
import { adminLogin, adminSetup, adminStatus } from "@/lib/api";
import { cn } from "@/lib/utils";
import { getAdminToken, setAdminToken } from "@/lib/adminAuth";

export default function AdminLoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [setupLoading, setSetupLoading] = useState(false);
  const [setupResult, setSetupResult] = useState<{ email: string; created: boolean } | null>(null);
  const [setupError, setSetupError] = useState<string | null>(null);
  // null = status not loaded yet (avoid flashing the init button for existing admins)
  const [adminInitialized, setAdminInitialized] = useState<boolean | null>(null);

  // Redirect already-authenticated users away from the login page.
  // Middleware handles this server-side too, but this covers client-side
  // navigations where middleware doesn't re-run.
  useEffect(() => {
    const token = getAdminToken();
    console.log("[ADMIN_AUTH] login page mount, token=%s", token ? "found" : "missing");
    if (token) {
      console.log("[ADMIN_REDIRECT] /admin/login → /admin (already authenticated)");
      router.replace("/admin");
    }
  }, [router]);

  // Hide "Initialize Admin Account" once an admin user already exists.
  useEffect(() => {
    let cancelled = false;
    adminStatus()
      .then((status) => {
        if (!cancelled) setAdminInitialized(status.initialized);
      })
      .catch(() => {
        // On failure, keep init available so first-time bootstrap remains possible.
        if (!cancelled) setAdminInitialized(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!email.trim() || !password.trim()) {
      setError("Email and password are required.");
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const result = await adminLogin(email.trim().toLowerCase(), password);
      // Store in both sessionStorage (layout guard) AND a cookie (middleware guard)
      setAdminToken(result.token);
      console.log("[ADMIN_REDIRECT] /admin/login → /admin (login success)");
      router.replace("/admin");
    } catch (err: unknown) {
      const msg =
        err instanceof Error
          ? err.message
          : "Invalid credentials. Please try again.";
      setError(msg);
    } finally {
      setLoading(false);
    }
  }

  async function handleSetup() {
    setSetupLoading(true);
    setSetupError(null);
    setSetupResult(null);
    try {
      const result = await adminSetup();
      setAdminInitialized(true);
      if (result.created) {
        setSetupResult(result);
        if (result.email) setEmail(result.email);
      }
      // If already existed, hide the init UI with no extra message.
    } catch (err: unknown) {
      setSetupError(
        err instanceof Error ? err.message : "Setup failed. Please try again."
      );
    } finally {
      setSetupLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#f5f7fb] via-blue-50/30 to-cyan-50/20 flex items-center justify-center p-4">
      <motion.div
        initial={{ opacity: 0, y: 24 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, ease: "easeOut" }}
        className="w-full max-w-md"
      >
        <div className="rounded-[32px] bg-white border border-gray-200/60 shadow-2xl overflow-hidden">
          {/* Header */}
          <div className="bg-gradient-to-r from-blue-600 to-cyan-500 px-8 py-8">
            <div className="w-14 h-14 rounded-2xl bg-white/20 flex items-center justify-center mb-4 shadow-lg">
              <Shield className="w-7 h-7 text-white" />
            </div>
            <h1 className="text-2xl font-black text-white">Admin Login</h1>
            <p className="text-sm text-blue-100 mt-1">DriveHub Platform Dashboard</p>
          </div>

          {/* Form */}
          <div className="px-8 py-7">
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -8 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex items-center gap-3 rounded-2xl bg-red-50 border border-red-200 px-4 py-3 mb-5 text-sm text-red-700"
              >
                <AlertCircle className="w-4 h-4 shrink-0" />
                {error}
              </motion.div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Email */}
              <div>
                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">
                  Email
                </label>
                <div className="relative">
                  <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="email"
                    placeholder="admin@drivehub.in"
                    value={email}
                    onChange={(e) => { setEmail(e.target.value); setError(null); }}
                    autoComplete="email"
                    className="w-full rounded-2xl border border-gray-200 bg-gray-50 px-4 py-3 pl-11 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white transition-colors"
                  />
                </div>
              </div>

              {/* Password */}
              <div>
                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">
                  Password
                </label>
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type={showPassword ? "text" : "password"}
                    placeholder="Your admin password"
                    value={password}
                    onChange={(e) => { setPassword(e.target.value); setError(null); }}
                    autoComplete="current-password"
                    className="w-full rounded-2xl border border-gray-200 bg-gray-50 px-4 py-3 pl-11 pr-11 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white transition-colors"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((v) => !v)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {/* Submit */}
              <motion.button
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                type="submit"
                disabled={loading}
                className="w-full bg-gradient-to-r from-blue-600 to-cyan-500 text-white font-bold py-4 rounded-2xl shadow-xl shadow-blue-100 flex items-center justify-center gap-2 disabled:opacity-80 transition-all mt-6"
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Signing in…
                  </>
                ) : (
                  "Sign In"
                )}
              </motion.button>
            </form>

            {/* Setup section — only when no admin exists yet (or right after first create) */}
            {(adminInitialized === false || setupResult?.created) && (
            <div className="mt-6 pt-6 border-t border-gray-100">
              {setupResult?.created && (
                <motion.div
                  initial={{ opacity: 0, y: -8 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="rounded-2xl bg-green-50 border border-green-200 px-4 py-3 mb-4 text-sm"
                >
                  <div className="flex items-center gap-2 text-green-700 font-bold mb-1">
                    <CheckCircle2 className="w-4 h-4" />
                    Admin account created!
                  </div>
                  <p className="text-green-600 text-xs">
                    Email: <span className="font-bold font-mono">{setupResult.email}</span>
                  </p>
                  <p className="text-green-600 text-xs mt-0.5">
                    Default password: <span className="font-bold font-mono">admin123</span> (change after first login)
                  </p>
                </motion.div>
              )}

              {setupError && (
                <div className="rounded-2xl bg-red-50 border border-red-200 px-4 py-3 mb-4 text-sm text-red-700">
                  {setupError}
                </div>
              )}

              {adminInitialized === false && (
                <>
                  <p className="text-sm text-gray-500 text-center mb-3">First time?</p>
                  <button
                    type="button"
                    onClick={handleSetup}
                    disabled={setupLoading}
                    className={cn(
                      "w-full py-3 rounded-2xl border border-gray-200 text-sm font-semibold text-gray-700 hover:border-blue-300 hover:text-blue-600 transition-all flex items-center justify-center gap-2",
                      setupLoading && "opacity-70 cursor-not-allowed"
                    )}
                  >
                    {setupLoading ? (
                      <>
                        <Loader2 className="w-4 h-4 animate-spin" />
                        Initializing…
                      </>
                    ) : (
                      "Initialize Admin Account"
                    )}
                  </button>
                </>
              )}
            </div>
            )}
          </div>
        </div>
      </motion.div>
    </div>
  );
}
