"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { LogIn } from "lucide-react";

export default function AdminPage() {
  const { user, loading, login, isSuperAdmin, permissions } = useAuth();
  const router = useRouter();
  const [error, setError] = useState("");
  const [loggingIn, setLoggingIn] = useState(false);

  useEffect(() => {
    if (loading) return;
    if (!user) return;
    if (isSuperAdmin || permissions.length > 0) {
      router.push("/admin/overview");
    } else {
      router.push("/dashboard");
    }
  }, [user, loading, isSuperAdmin, permissions, router]);

  const handleLogin = async () => {
    setError("");
    setLoggingIn(true);
    try {
      await login();
    } catch (err: any) {
      setError(err.message || "Login failed");
    } finally {
      setLoggingIn(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">Loading...</div>
      </div>
    );
  }

  if (user) return null;

  return (
    <div className="flex items-center justify-center min-h-[60vh]">
      <div className="bg-surface-container-low rounded-xl p-8 max-w-md w-full text-center">
        <h1 className="text-2xl font-bold text-on-surface mb-2">Admin Dashboard</h1>
        <p className="text-on-surface/60 mb-6">
          Sign in with your Nostr identity to access the admin panel.
        </p>

        <button
          onClick={handleLogin}
          disabled={loggingIn}
          className="w-full flex items-center justify-center gap-3 px-6 py-3 rounded-lg font-semibold transition-all bg-gradient-to-r from-primary to-primary-container text-on-primary hover:opacity-90 disabled:opacity-50"
        >
          <LogIn size={20} />
          {loggingIn ? "Connecting..." : "Login with Nostr"}
        </button>

        {error && (
          <p className="mt-4 text-error text-sm">{error}</p>
        )}

        <p className="mt-6 text-on-surface/40 text-xs leading-relaxed">
          You need a Nostr browser extension (e.g. Alby, nos2x, or Flamingo) to sign in.
          Your pubkey must be registered as an admin or moderator.
        </p>
      </div>
    </div>
  );
}
