import { useCallback, useEffect, useState } from 'react';
import { isCancel } from 'axios';
import axios from '../../../bootstrap';
import {
    confirmedMalwareCount,
    formatScanTime,
    MalwareReportRow,
    MalwareThreatFile,
    normalizeThreatFiles,
    resolveThreatSummary,
    scanStatusLabel,
    statusBadgeClass,
} from '../../../utils/malwareReport';
import { canVerifySafe, VerifySafeDialog } from './VerifySafeDialog';
import { VerifySafeAction } from './VerifySafeAction';
import { enrichThreatFileForVerify } from '../../../utils/malwareReport';

interface MalwareReportsViewProps {
    /** Hide page title when rendered inside Security Events tabs */
    embedded?: boolean;
    agentId?: string;
}

export function MalwareReportsView({ embedded = false, agentId }: MalwareReportsViewProps) {
    const [reports, setReports] = useState<MalwareReportRow[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [verifyTarget, setVerifyTarget] = useState<MalwareThreatFile | null>(null);
    const [verifyReportId, setVerifyReportId] = useState<number | null>(null);
    const [verifySubmitting, setVerifySubmitting] = useState(false);
    const [verifySuccess, setVerifySuccess] = useState<string | null>(null);

    const fetchReports = useCallback(async (signal?: AbortSignal) => {
        setIsLoading(true);
        setError(null);

        try {
            const query = agentId ? `?agent_id=${encodeURIComponent(agentId)}` : '';
            const res = await axios.get(`/malware-reports${query}`, { signal });
            setReports(res.data.reports || []);
        } catch (err: unknown) {
            if (isCancel(err)) {
                return;
            }

            console.error('Error fetching malware reports', err);
            setReports([]);
            setError('Could not load malware scan reports. Please refresh and try again.');
        } finally {
            if (!signal?.aborted) {
                setIsLoading(false);
            }
        }
    }, [agentId]);

    useEffect(() => {
        const controller = new AbortController();
        fetchReports(controller.signal);
        return () => controller.abort();
    }, [fetchReports]);

    const submitVerifySafe = async () => {
        if (!verifyTarget || !canVerifySafe(verifyTarget)) {
            return;
        }

        const target = enrichThreatFileForVerify(verifyTarget);

        setVerifySubmitting(true);
        setError(null);

        try {
            await axios.post('/verified-safe-files', {
                malware_report_id: verifyReportId,
                finding_path: target.path,
                plugin_slug: target.plugin_slug,
                plugin_name: target.plugin_name,
                plugin_version: target.plugin_version,
                relative_path: target.relative_path,
                sha256: target.sha256,
                detection_rule: verifyTarget.detection_rule || verifyTarget.indicators?.[0] || null,
                status_label: verifyTarget.status_label,
                classification: verifyTarget.classification,
                score: verifyTarget.score,
            });

            setVerifySuccess('Fingerprint verified safe. Agents will sync on next heartbeat.');
            setVerifyTarget(null);
        } catch (err: unknown) {
            const message = (err as { response?: { data?: { message?: string; errors?: Record<string, string[]> } } })?.response?.data;
            const firstError = message?.errors ? Object.values(message.errors)[0]?.[0] : null;
            setError(firstError || message?.message || 'Could not verify this fingerprint.');
        } finally {
            setVerifySubmitting(false);
        }
    };

    return (
        <div className="space-y-6">
            {!embedded && (
                <div>
                    <h3 className="text-xl font-bold text-white">Malware Scan Summaries</h3>
                    <p className="text-sm text-slate-400">Enterprise-weighted scan results with vendor integrity analysis</p>
                </div>
            )}

            {error && (
                <div className="rounded-2xl border border-rose-500/20 bg-rose-500/5 px-4 py-3 text-sm text-rose-300">
                    {error}
                </div>
            )}

            {verifySuccess && (
                <div className="rounded-2xl border border-emerald-500/20 bg-emerald-500/5 px-4 py-3 text-sm text-emerald-300">
                    {verifySuccess}
                </div>
            )}

            <div className="bg-slate-900/40 border border-slate-800/80 rounded-2xl overflow-hidden">
                {isLoading ? (
                    <div className="flex justify-center items-center py-16">
                        <div className="w-8 h-8 border-4 border-rose-500/20 border-t-rose-500 rounded-full animate-spin"></div>
                    </div>
                ) : reports.length === 0 ? (
                    <div className="text-center py-16 text-slate-500 text-sm">
                        No malware scan reports ingested yet.
                    </div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr className="border-b border-slate-800 text-xs font-semibold text-slate-400 uppercase bg-slate-900/20">
                                    <th className="py-3.5 px-4">Website</th>
                                    <th className="py-3.5 px-4">Files Scanned</th>
                                    <th className="py-3.5 px-4">Scan Result</th>
                                    <th className="py-3.5 px-4">Scan Time</th>
                                    <th className="py-3.5 px-4">Findings</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-800/60 text-sm text-slate-300">
                                {reports.map((report) => {
                                    const threatFiles = normalizeThreatFiles(
                                        report.threat_details,
                                        report.threat_files,
                                    );
                                    const summary = resolveThreatSummary(report, threatFiles);
                                    const confirmed = confirmedMalwareCount(report, threatFiles);
                                    const resultLabel = scanStatusLabel(report, threatFiles);

                                    return (
                                        <tr key={report.id} className="hover:bg-slate-800/10">
                                            <td className="py-3.5 px-4 font-semibold text-white">
                                                {report.agent?.site_name || 'Unknown site'}
                                            </td>
                                            <td className="py-3.5 px-4 font-mono text-xs">{report.files_scanned} files</td>
                                            <td className="py-3.5 px-4">
                                                <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border ${
                                                    confirmed > 0
                                                        ? 'bg-rose-500/10 text-rose-400 border-rose-500/20 animate-pulse'
                                                        : summary.total_findings > 0
                                                            ? 'bg-amber-500/10 text-amber-300 border-amber-500/20'
                                                            : 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20'
                                                }`}>
                                                    {resultLabel}
                                                </span>
                                            </td>
                                            <td className="py-3.5 px-4 text-xs text-slate-500">
                                                {formatScanTime(report.scanned_at)}
                                            </td>
                                            <td className="py-3.5 px-4 text-xs max-w-md">
                                                {threatFiles.length > 0 ? (
                                                    <div className="space-y-2">
                                                        {threatFiles.map((threat, idx) => (
                                                            <div
                                                                key={`${report.id}-${idx}`}
                                                                className={`rounded-lg border p-2 ${statusBadgeClass(threat.status_label ?? '', threat.classification)}`}
                                                            >
                                                                <div className="flex flex-wrap items-center gap-2">
                                                                    <span className="text-[10px] font-bold uppercase">
                                                                        {threat.status_label ?? 'Finding'}
                                                                    </span>
                                                                    {threat.score !== null && (
                                                                        <span className="text-[10px] opacity-80">Score {threat.score}</span>
                                                                    )}
                                                                </div>
                                                                <div className="font-mono text-[10px] truncate mt-1" title={threat.path}>
                                                                    {threat.path || threat.type}
                                                                </div>
                                                                {threat.verification_history_note && (
                                                                    <div className="text-[10px] text-amber-300/90 mt-1 leading-relaxed">
                                                                        {threat.verification_history_note}
                                                                    </div>
                                                                )}
                                                                {threat.indicators && threat.indicators.length > 0 && (
                                                                    <div className="text-[10px] opacity-80 mt-1 truncate" title={threat.indicators.join(', ')}>
                                                                        Indicators: {threat.indicators.join(', ')}
                                                                    </div>
                                                                )}
                                                                <VerifySafeAction
                                                                    file={threat}
                                                                    compact
                                                                    onVerify={(selected) => {
                                                                        setVerifySuccess(null);
                                                                        setVerifyTarget(selected);
                                                                        setVerifyReportId(report.id);
                                                                    }}
                                                                />
                                                            </div>
                                                        ))}
                                                    </div>
                                                ) : (
                                                    <span className="text-slate-500">No actionable findings</span>
                                                )}
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            <VerifySafeDialog
                threat={verifyTarget ?? { path: '', type: '', score: null }}
                open={verifyTarget !== null}
                onCancel={() => setVerifyTarget(null)}
                onConfirm={submitVerifySafe}
                isSubmitting={verifySubmitting}
            />
        </div>
    );
}
