import { enrichThreatFileForVerify, MalwareThreatFile } from '../../../utils/malwareReport';

export type VerifySafeState =
    | { kind: 'ready' }
    | { kind: 'blocked'; reason: string }
    | { kind: 'rescan_required'; reason: string };

function isNeedsVerificationStatus(statusLabel: string | undefined): boolean {
    return (statusLabel ?? '').trim().toLowerCase() === 'needs verification';
}

function isConfirmedMalware(file: MalwareThreatFile): boolean {
    return file.classification === 'malware'
        || (file.status_label ?? '').trim().toLowerCase() === 'confirmed malware'
        || (file.score !== null && file.score >= 70);
}

export function resolveVerifySafeState(file: MalwareThreatFile): VerifySafeState {
    const enriched = enrichThreatFileForVerify(file);

    if (enriched.classification === 'malware' || enriched.status_label === 'Confirmed Malware') {
        return {
            kind: 'blocked',
            reason: 'Confirmed malware cannot be marked safe. If this is a known library false positive, deploy scanner engine 2.4+ on the site and run a new malware scan — the status should change to Needs Verification, then you can mark it safe.',
        };
    }

    if (enriched.score !== null && enriched.score >= 70) {
        return {
            kind: 'blocked',
            reason: 'High-confidence threats cannot be marked safe. Investigate or remove the file instead of trusting it.',
        };
    }

    if (!isNeedsVerificationStatus(enriched.status_label)) {
        const label = enriched.status_label ?? 'this finding';

        return {
            kind: 'blocked',
            reason: `Only Needs Verification findings can be marked safe (current: ${label}). Run a new scan after updating the site plugin if you expect a lower severity.`,
        };
    }

    const missing: string[] = [];

    if (!enriched.plugin_slug) {
        missing.push('plugin');
    }

    if (!enriched.plugin_version) {
        missing.push('plugin version');
    }

    if (!enriched.relative_path) {
        missing.push('relative path');
    }

    if (!enriched.sha256) {
        missing.push('SHA-256 hash');
    }

    if (missing.length > 0) {
        return {
            kind: 'rescan_required',
            reason: `Missing ${missing.join(', ')}. Run a new malware scan with plugin v1.2.7+ on this site, then try again.`,
        };
    }

    return { kind: 'ready' };
}

export function shouldShowVerifySafeAction(file: MalwareThreatFile): boolean {
    return resolveVerifySafeState(file).kind === 'ready';
}

export function shouldShowTrustGuidance(file: MalwareThreatFile): boolean {
    return resolveVerifySafeState(file).kind !== 'ready';
}

export function canVerifySafe(threat: MalwareThreatFile): boolean {
    return resolveVerifySafeState(threat).kind === 'ready';
}

interface VerifySafeActionProps {
    file: MalwareThreatFile;
    onVerify: (file: MalwareThreatFile) => void;
    compact?: boolean;
}

export function VerifySafeAction({ file, onVerify, compact = false }: VerifySafeActionProps) {
    const enriched = enrichThreatFileForVerify(file);
    const state = resolveVerifySafeState(enriched);

    if (state.kind === 'ready') {
        return (
            <div className="font-sans">
                <button
                    type="button"
                    onClick={() => onVerify(enriched)}
                    className={
                        compact
                            ? 'inline-flex items-center rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-2.5 py-1 text-[10px] font-bold uppercase text-emerald-300 hover:bg-emerald-500/20'
                            : 'inline-flex items-center rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-1.5 text-[11px] font-bold uppercase text-emerald-300 hover:bg-emerald-500/20'
                    }
                >
                    ✓ Mark as Safe / Trusted
                </button>
            </div>
        );
    }

    const tone = isConfirmedMalware(enriched) ? 'text-rose-300/90' : 'text-amber-300/90';

    return (
        <p className={`text-[10px] leading-relaxed font-sans max-w-2xl ${tone}`}>
            {state.reason}
        </p>
    );
}
