"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Lock, Loader2, AlertCircle, CheckCircle2 } from "lucide-react";
import Logo from "@/components/Logo";

export default function LoginPage() {
    const [password, setPassword] = useState("");
    const [loading, setLoading] = useState(false);
    const [success, setSuccess] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const router = useRouter();

    // Auto-redirect if already logged in
    useEffect(() => {
        const token = localStorage.getItem("mhb_token");
        if (token) router.replace("/");
    }, []);

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!password || loading) return;
        setLoading(true);
        setError(null);

        try {
            const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
            const res = await fetch(`${API_URL}/api/auth/login`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ password }),
            });

            const data = await res.json();

            if (res.ok) {
                localStorage.setItem("mhb_token", data.token);
                document.cookie = `mhb_token=${data.token}; path=/; max-age=86400; SameSite=Lax`;
                setSuccess(true);
                // Hard redirect to dashboard to ensure cookie/middleware sync
                setTimeout(() => {
                    window.location.href = "/";
                }, 800);
            } else {
                setError(data.error || "Invalid password");
            }
        } catch {
            setError("Cannot connect to server. Is the backend running?");
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen w-full bg-bg-primary flex items-center justify-center p-6 relative overflow-hidden">

            {/* Subtle ambient background */}
            <div className="absolute inset-0 pointer-events-none">
                <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-accent-cyan/5 rounded-full blur-[100px]" />
                <div className="absolute top-1/4 right-1/4 w-[200px] h-[200px] bg-accent-violet/5 rounded-full blur-[80px]" />
            </div>

            {/* Login card */}
            <div className="relative z-10 w-full max-w-sm animate-fade-in">

                {/* Logo */}
                <div className="flex justify-center mb-10">
                    <Logo size="md" />
                </div>

                {/* Card */}
                <div className="bg-bg-secondary border border-white/5 rounded-2xl p-8 shadow-2xl">
                    {success ? (
                        <div className="flex flex-col items-center gap-4 py-4 animate-fade-in">
                            <CheckCircle2 className="w-12 h-12 text-emerald-400" />
                            <p className="text-white font-semibold text-sm">Access Granted</p>
                            <p className="text-white/30 text-xs">Loading dashboard...</p>
                        </div>
                    ) : (
                        <form onSubmit={handleLogin} className="space-y-5">
                            <div>
                                <label className="block text-[10px] font-bold uppercase tracking-widest text-white/30 mb-2">
                                    Admin Password
                                </label>
                                <div className="relative">
                                    <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/20" />
                                    <input
                                        type="password"
                                        autoFocus
                                        required
                                        value={password}
                                        onChange={(e) => {
                                            setPassword(e.target.value);
                                            if (error) setError(null);
                                        }}
                                        placeholder="Enter password..."
                                        className="w-full bg-bg-card border border-white/5 rounded-xl pl-11 pr-4 h-12 text-white text-sm placeholder:text-white/20 focus:outline-none focus:border-accent-cyan/40 focus:bg-accent-cyan/[0.02] transition-all"
                                    />
                                </div>
                            </div>

                            {error && (
                                <div className="flex items-center gap-2.5 p-3 rounded-xl bg-red-500/10 border border-red-500/10 text-red-400 text-xs">
                                    <AlertCircle className="w-4 h-4 shrink-0" />
                                    <span className="font-semibold">{error}</span>
                                </div>
                            )}

                            <button
                                type="submit"
                                disabled={loading || !password}
                                className="w-full h-12 bg-accent-cyan hover:bg-accent-cyan/90 disabled:opacity-40 disabled:cursor-not-allowed text-white font-bold text-sm uppercase tracking-widest rounded-xl transition-all flex items-center justify-center gap-2"
                            >
                                {loading ? (
                                    <Loader2 className="w-5 h-5 animate-spin" />
                                ) : (
                                    "Sign In"
                                )}
                            </button>
                        </form>
                    )}
                </div>

                <p className="text-center mt-6 text-[10px] text-white/15 font-medium uppercase tracking-widest">
                    Authorized Access Only
                </p>
            </div>
        </div>
    );
}
