"use client";

import { useState, useEffect } from "react";
import { AlertTriangle, Activity, RefreshCw } from "lucide-react";
import toast from "react-hot-toast";

type SecurityAnomaly = {
    id: string;
    ruleName: string;
    severity: "MEDIUM" | "HIGH" | "CRITICAL";
    description: string;
    detectedAt: string;
    relatedAdminId?: string;
    evidenceCount: number;
};

export default function ActivityMonitoringPanel() {
    const [anomalies, setAnomalies] = useState<SecurityAnomaly[]>([]);
    const [loading, setLoading] = useState(true);

    const fetchAnomalies = async () => {
        setLoading(true);
        try {
            const res = await fetch("/api/admin/logs/anomalies");
            if (!res.ok) throw new Error("Failed to fetch anomalies");
            const data = await res.json();
            setAnomalies(data.anomalies || []);
        } catch (error: any) {
            toast.error("Could not load security anomalies");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchAnomalies();

        // Polling every 60 seconds
        const interval = setInterval(fetchAnomalies, 60000);
        return () => clearInterval(interval);
    }, []);

    const getSeverityStyles = (severity: string) => {
        switch (severity) {
            case "CRITICAL": return "bg-red-100 text-red-800 border-red-200";
            case "HIGH": return "bg-orange-100 text-orange-800 border-orange-200";
            case "MEDIUM": return "bg-yellow-100 text-yellow-800 border-yellow-200";
            default: return "bg-slate-100 text-slate-800 border-slate-200";
        }
    };

    return (
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mt-6">
            <div className="flex items-start justify-between mb-6">
                <div>
                    <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
                        <Activity className="w-5 h-5 text-indigo-600" />
                        Real-Time Anomaly Dashboard
                    </h2>
                    <p className="text-sm text-slate-500 mt-1 max-w-2xl">
                        Continuous monitoring of the 24-hour log buffer to detect suspicious administrative behavior patterns, privilege escalation, and credential abuse.
                    </p>
                </div>
                <button
                    onClick={fetchAnomalies}
                    disabled={loading}
                    className="p-2 text-slate-400 hover:text-indigo-600 rounded-lg hover:bg-slate-50 transition-colors"
                    title="Refresh Anomalies"
                >
                    <RefreshCw className={`w-5 h-5 ${loading ? "animate-spin" : ""}`} />
                </button>
            </div>

            {loading && anomalies.length === 0 ? (
                <div className="flex justify-center items-center h-32 text-slate-400">
                    <RefreshCw className="w-6 h-6 animate-spin" />
                </div>
            ) : anomalies.length === 0 ? (
                <div className="rounded-xl border-2 border-dashed border-emerald-200 bg-emerald-50/50 p-8 text-center text-emerald-800">
                    <div className="bg-emerald-100 w-12 h-12 rounded-full flex items-center justify-center mx-auto mb-3">
                        <Activity className="w-6 h-6 text-emerald-600" />
                    </div>
                    <h3 className="font-bold">No Anomalies Detected</h3>
                    <p className="text-sm text-emerald-600 mt-1">Activity patterns appear normal. No suspicious rules were triggered in the last 24 hours.</p>
                </div>
            ) : (
                <div className="space-y-4">
                    {anomalies.map((anomaly) => (
                        <div key={anomaly.id} className={`p-4 rounded-lg border ${getSeverityStyles(anomaly.severity)}`}>
                            <div className="flex items-start gap-3">
                                <AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
                                <div>
                                    <div className="flex items-center gap-2">
                                        <h4 className="font-bold">{anomaly.ruleName}</h4>
                                        <span className="text-[10px] uppercase font-bold px-2 py-0.5 rounded-full bg-white/50 border border-current/20">
                                            {anomaly.severity}
                                        </span>
                                    </div>
                                    <p className="text-sm mt-1 opacity-90">{anomaly.description}</p>

                                    <div className="flex items-center gap-4 mt-3 text-xs font-medium opacity-75">
                                        <span>Triggered at: {new Date(anomaly.detectedAt).toLocaleTimeString()}</span>
                                        <span>Evidence Nodes: {anomaly.evidenceCount}</span>
                                        {anomaly.relatedAdminId && (
                                            <span className="px-2 py-0.5 bg-black/5 rounded">
                                                Admin ID: <span className="font-mono">{anomaly.relatedAdminId.substring(0, 8)}...</span>
                                            </span>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
