"use client";
import { useState, useEffect } from "react";
import { Shield, QrCode, Check, AlertCircle, Loader2, Eye, EyeOff, Trash2 } from "lucide-react";
import { useUI } from "@/context/UIContext";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";

export default function TwoFASettingsPage() {
    const { toast, alert } = useUI();
    const [status, setStatus] = useState<{ enabled: boolean; hasSecret: boolean } | null>(null);
    const [setupData, setSetupData] = useState<{ secret: string; otpUri: string } | null>(null);
    const [token, setToken] = useState("");
    const [password, setPassword] = useState("");
    const [showPass, setShowPass] = useState(false);
    const [loading, setLoading] = useState(false);
    const [qrUrl, setQrUrl] = useState("");

    const authHeaders = () => ({
        "Content-Type": "application/json",
        Authorization: `Bearer ${localStorage.getItem("mhb_token") || ""}`
    });

    async function load2FAStatus() {
        const res = await fetch(`${API}/api/auth/2fa/status`, { headers: authHeaders() });
        const data = await res.json();
        setStatus(data);
    }

    useEffect(() => { load2FAStatus(); }, []);

    async function handleSetup() {
        setLoading(true);
        try {
            const res = await fetch(`${API}/api/auth/2fa/setup`, { method: "POST", headers: authHeaders() });
            const data = await res.json();
            if (!data.success) throw new Error(data.error);
            setSetupData({ secret: data.secret, otpUri: data.otpUri });
            // QR code via Google Charts API (no server-side QR dependency)
            setQrUrl(`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(data.otpUri)}`);
        } catch (e: any) { alert({ title: "Setup Failed", message: e.message, type: "error" }); }
        setLoading(false);
    }

    async function handleVerify() {
        setLoading(true);
        try {
            const res = await fetch(`${API}/api/auth/2fa/verify`, {
                method: "POST", headers: authHeaders(),
                body: JSON.stringify({ token }),
            });
            const data = await res.json();
            if (!data.success) throw new Error(data.error);
            toast("2FA enabled! You will be prompted on next login.", "success");
            setSetupData(null); setToken(""); load2FAStatus();
        } catch (e: any) { alert({ title: "Verification Failed", message: e.message, type: "error" }); }
        setLoading(false);
    }

    async function handleDisable() {
        if (!confirm("Disable 2FA? This reduces security.")) return;
        setLoading(true);
        try {
            const res = await fetch(`${API}/api/auth/2fa/disable`, {
                method: "POST", headers: authHeaders(),
                body: JSON.stringify({ token, password }),
            });
            const data = await res.json();
            if (!data.success) throw new Error(data.error);
            toast("2FA disabled.", "info");
            setToken(""); setPassword(""); load2FAStatus();
        } catch (e: any) { alert({ title: "Disable Failed", message: e.message, type: "error" }); }
        setLoading(false);
    }

    return (
        <div className="space-y-8 max-w-lg mx-auto pb-20">
            <div className="flex items-center gap-4">
                <div className="w-12 h-12 rounded-2xl bg-emerald-500/10 flex items-center justify-center">
                    <Shield className="w-6 h-6 text-emerald-400" />
                </div>
                <div>
                    <h1 className="text-2xl font-extrabold text-white">Two-Factor Authentication</h1>
                    <p className="text-white/40 text-sm">Protect your dashboard with TOTP (Google Authenticator, Authy).</p>
                </div>
            </div>

            {/* Status */}
            {status && (
                <div className={`flex items-center gap-3 p-4 rounded-2xl border ${status.enabled ? "bg-emerald-500/5 border-emerald-500/20" : "bg-white/5 border-white/10"}`}>
                    {status.enabled ? <Check className="w-5 h-5 text-emerald-400" /> : <AlertCircle className="w-5 h-5 text-white/30" />}
                    <div>
                        <p className="font-black text-white text-sm">{status.enabled ? "2FA is Active" : "2FA is Disabled"}</p>
                        <p className="text-xs text-white/40">{status.enabled ? "Your account requires a TOTP code on login." : "Your account is protected by password only."}</p>
                    </div>
                </div>
            )}

            {/* Setup flow */}
            {!status?.enabled && !setupData && (
                <button onClick={handleSetup} disabled={loading} className="btn-primary w-full py-4 flex items-center justify-center gap-2">
                    {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <QrCode className="w-4 h-4" />}
                    Set Up Two-Factor Auth
                </button>
            )}

            {setupData && (
                <div className="card p-6 bg-black/40 border-white/10 space-y-5">
                    <h2 className="font-black text-white">Step 1: Scan QR Code</h2>
                    {qrUrl && <img src={qrUrl} alt="QR Code" className="w-48 h-48 rounded-xl mx-auto bg-white p-2" />}
                    <div>
                        <p className="text-xs text-white/40 mb-1">Or enter manually:</p>
                        <code className="block bg-white/5 rounded-lg px-3 py-2 text-xs font-mono text-accent-cyan break-all">{setupData.secret}</code>
                    </div>
                    <div>
                        <h3 className="font-black text-white mb-2">Step 2: Enter Code to Verify</h3>
                        <input
                            type="text" inputMode="numeric" maxLength={6}
                            value={token} onChange={e => setToken(e.target.value.replace(/\D/g, ''))}
                            placeholder="000000"
                            className="input w-full text-center text-2xl font-mono tracking-widest"
                        />
                    </div>
                    <button onClick={handleVerify} disabled={token.length !== 6 || loading} className="btn-primary w-full py-3">
                        {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />} Enable 2FA
                    </button>
                </div>
            )}

            {/* Disable flow */}
            {status?.enabled && (
                <div className="card p-6 bg-black/40 border-red-500/10 space-y-4">
                    <h2 className="font-black text-white text-sm">Disable 2FA</h2>
                    <div className="space-y-3">
                        <input
                            type="text" inputMode="numeric" maxLength={6}
                            value={token} onChange={e => setToken(e.target.value.replace(/\D/g, ''))}
                            placeholder="Current TOTP code"
                            className="input w-full text-center font-mono tracking-widest"
                        />
                        <div className="relative">
                            <input
                                type={showPass ? "text" : "password"}
                                value={password} onChange={e => setPassword(e.target.value)}
                                placeholder="Admin password"
                                className="input w-full pr-10"
                            />
                            <button onClick={() => setShowPass(s => !s)} className="absolute right-3 top-1/2 -translate-y-1/2 text-white/30 hover:text-white">
                                {showPass ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                            </button>
                        </div>
                        <button onClick={handleDisable} disabled={token.length !== 6 || !password || loading} className="w-full py-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 font-black hover:bg-red-500/20 disabled:opacity-40 flex items-center justify-center gap-2">
                            <Trash2 className="w-4 h-4" /> Disable 2FA
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}
