"use strict";
"use client";

import { useState } from "react";
import { ShieldAlert, ShieldCheck, Asterisk, Play, RefreshCcw, Lock } from "lucide-react";

interface IntegrityResult {
    intact: boolean;
    message: string;
    totalVerified: number;
    brokenAtId?: string;
}

export default function SecurityIntegrityPanel() {
    const [isScanning, setIsScanning] = useState(false);
    const [result, setResult] = useState<IntegrityResult | null>(null);
    const [lastScan, setLastScan] = useState<Date | null>(null);

    const runIntegrityScan = async () => {
        setIsScanning(true);
        setResult(null);

        try {
            const response = await fetch("/api/admin/logs/integrity");
            // Even if it's 409 (tampered), we want the JSON body
            const data = await response.json();
            setResult(data);
            setLastScan(new Date());
        } catch (error) {
            console.error("Scan failed", error);
        } finally {
            setIsScanning(false);
        }
    };

    return (
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
            <div className="flex items-start justify-between mb-8">
                <div>
                    <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
                        <Lock className="w-5 h-5 text-indigo-600" />
                        WORM Integrity Scanner
                    </h2>
                    <p className="text-sm text-slate-500 mt-1 max-w-2xl">
                        Activity logs are cryptographically chained using SHA-256 hashes. This ensures "Write-Once-Read-Many" (WORM) compliance. Scanning the chain recalculates every hash to detect database tampering.
                    </p>
                </div>
                <button
                    onClick={runIntegrityScan}
                    disabled={isScanning}
                    className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 transition-colors font-medium shadow-sm"
                >
                    {isScanning ? (
                        <RefreshCcw className="w-4 h-4 animate-spin" />
                    ) : (
                        <Play className="w-4 h-4" />
                    )}
                    {isScanning ? "Scanning Chain..." : "Run Integrity Scan"}
                </button>
            </div>

            {result ? (
                <div className={`rounded-xl border p-6 ${result.intact ? 'bg-emerald-50 border-emerald-200' : 'bg-red-50 border-red-200 shadow-sm'}`}>
                    <div className="flex items-start gap-4">
                        <div className={`p-3 rounded-full ${result.intact ? 'bg-emerald-100 text-emerald-600' : 'bg-red-100 text-red-600'}`}>
                            {result.intact ? <ShieldCheck className="w-8 h-8" /> : <ShieldAlert className="w-8 h-8" />}
                        </div>
                        <div className="flex-1">
                            <h3 className={`text-lg font-bold ${result.intact ? 'text-emerald-800' : 'text-red-800'}`}>
                                {result.intact ? "Chain Verified Intact" : "INTEGRITY VIOLATION DETECTED"}
                            </h3>
                            <p className={`mt-1 text-sm ${result.intact ? 'text-emerald-600' : 'text-red-600 font-medium'}`}>
                                {result.message}
                            </p>

                            <div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div className="bg-white/60 p-4 rounded-lg border border-white/50 backdrop-blur-sm">
                                    <span className="block text-xs uppercase tracking-wider font-semibold text-slate-500 mb-1">Logs Verified</span>
                                    <span className="text-2xl font-bold text-slate-800">{result.totalVerified.toLocaleString()}</span>
                                </div>
                                <div className="bg-white/60 p-4 rounded-lg border border-white/50 backdrop-blur-sm">
                                    <span className="block text-xs uppercase tracking-wider font-semibold text-slate-500 mb-1">Last Full Scan</span>
                                    <span className="text-sm font-medium text-slate-700">
                                        {lastScan?.toLocaleTimeString()}
                                    </span>
                                </div>
                                {!result.intact && result.brokenAtId && (
                                    <div className="bg-white/60 p-4 rounded-lg border border-red-200">
                                        <span className="block text-xs uppercase tracking-wider font-semibold text-red-500 mb-1">Breach Origin ID</span>
                                        <span className="text-xs font-mono bg-red-100 text-red-700 px-2 py-1 rounded inline-block">
                                            {result.brokenAtId}
                                        </span>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            ) : (
                <div className="h-64 rounded-xl border-2 border-dashed border-slate-200 flex flex-col items-center justify-center text-slate-400 bg-slate-50">
                    <Asterisk className="w-8 h-8 mb-4 opacity-50" />
                    <p className="font-medium">No scan results currently available.</p>
                    <p className="text-sm mt-1">Run a scan to verify the cryptographic chain.</p>
                </div>
            )}
        </div>
    );
}
