"use client";

import { Fragment, useEffect, useState } from 'react';
import api from '../../lib/api';
import { Asset, ScanRunSummary } from '../../types';
import { PlayIcon, ArrowPathIcon, ClockIcon, TrashIcon, ChevronDownIcon, ChevronRightIcon, PencilIcon } from '@heroicons/react/24/outline';

interface ScanSchedule {
    id: number;
    name: string;
    interval: string;
    cron_expression: string | null;
    scanner_type: string;
    enabled: boolean;
    last_run: string | null;
    next_run: string | null;
}

const INTERVAL_LABELS: Record<string, string> = {
    every_hour: 'Every Hour',
    every_6_hours: 'Every 6 Hours',
    every_12_hours: 'Every 12 Hours',
    daily: 'Daily',
    weekly: 'Weekly',
    cron: 'Custom Cron',
};

export default function ScansPage() {
    const [scanRuns, setScanRuns] = useState<ScanRunSummary[]>([]);
    const [assets, setAssets] = useState<Asset[]>([]);
    const [schedules, setSchedules] = useState<ScanSchedule[]>([]);
    const [loading, setLoading] = useState(true);
    const [expandedRun, setExpandedRun] = useState<number | null>(null);
    const [selectedRuns, setSelectedRuns] = useState<Set<number>>(new Set());
    const [isScheduleModalOpen, setIsScheduleModalOpen] = useState(false);
    const [newSchedule, setNewSchedule] = useState({ name: '', interval: 'daily', cron_expression: '', scanner_type: 'wazuh' });
    const [editingScheduleId, setEditingScheduleId] = useState<number | null>(null);
    const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' | 'info' } | null>(null);

    // Autoscan Modal State
    const [isAutoscanModalOpen, setIsAutoscanModalOpen] = useState(false);
    const [autoscanStatus, setAutoscanStatus] = useState<'idle' | 'running' | 'complete' | 'error'>('idle');
    const [autoscanResult, setAutoscanResult] = useState<{ message: string; scans_triggered: number; errors: string[] } | null>(null);

    // Sync Modal State
    const [isSyncModalOpen, setIsSyncModalOpen] = useState(false);
    const [syncStatus, setSyncStatus] = useState<'idle' | 'running' | 'complete' | 'error'>('idle');
    const [syncStep, setSyncStep] = useState<'assets' | 'vulns'>('assets'); // To track progress
    const [syncResult, setSyncResult] = useState<{ assetsCreated: number; assetsUpdated: number; vulnMessage: string } | null>(null);

    const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
        setToast({ message, type });
        setTimeout(() => setToast(null), 5000);
    };

    const fetchData = async () => {
        setLoading(true);
        try {
            const [summaryRes, assetsRes, schedulesRes] = await Promise.all([
                api.get('/api/v1/scans/summary'),
                api.get('/api/v1/assets'),
                api.get('/api/v1/scans/schedules')
            ]);
            setScanRuns(summaryRes.data);
            setAssets(assetsRes.data);
            setSchedules(schedulesRes.data);
        } catch (error) {
            console.error("Failed to fetch data:", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    const handleAutoscan = async () => {
        setIsAutoscanModalOpen(true);
        setAutoscanStatus('running');
        setAutoscanResult(null);

        try {
            const res = await api.post('/api/v1/scans/autoscan');
            setAutoscanResult(res.data);
            setAutoscanStatus('complete');
            fetchData();
        } catch (error: any) {
            console.error("Autoscan failed:", error);
            setAutoscanResult({ message: error.response?.data?.detail || "Failed to trigger autoscan.", scans_triggered: 0, errors: [error.message] });
            setAutoscanStatus('error');
        }
    };

    const [nessusSyncing, setNessusSyncing] = useState(false);

    const handleNessusSync = async () => {
        if (nessusSyncing) return;
        if (!confirm('Trigger Nessus sync now? Imports findings from the scans configured in Settings.')) return;
        setNessusSyncing(true);
        try {
            const res = await api.post('/api/v1/vulnerabilities/nessus/sync', {});
            const s = res.data || {};
            setToast({
                message: `Nessus sync done: ${s.vulns_created || 0} created, ${s.vulns_merged || 0} merged, ${s.hosts_synced || 0} hosts, ${(s.unmatched_hosts || []).length} unmatched.`,
                type: 'success',
            });
            fetchData();
        } catch (e: any) {
            setToast({
                message: e?.response?.data?.detail || 'Nessus sync failed (check Settings → Tenable Nessus is configured).',
                type: 'error',
            });
        } finally {
            setNessusSyncing(false);
        }
    };

    const handleSync = async () => {
        setIsSyncModalOpen(true);
        setSyncStatus('running');
        setSyncStep('assets');
        setSyncResult(null);

        try {
            // Sync assets first
            const assetRes = await api.post('/api/v1/assets/sync_wazuh');

            setSyncStep('vulns');
            // Then sync vulnerabilities
            const vulnRes = await api.post('/api/v1/vulnerabilities/sync/wazuh');

            setSyncResult({
                assetsCreated: assetRes.data.created,
                assetsUpdated: assetRes.data.updated,
                vulnMessage: vulnRes.data.message
            });
            setSyncStatus('complete');
            fetchData();
        } catch (error: any) {
            console.error("Sync failed:", error);
            setToast({ message: error.response?.data?.detail || "Failed to sync with Wazuh.", type: 'error' });
            setSyncStatus('error');
        }
    };

    const handleCreateSchedule = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            if (editingScheduleId) {
                await api.put(`/api/v1/scans/schedules/${editingScheduleId}`, newSchedule);
            } else {
                await api.post('/api/v1/scans/schedules', newSchedule);
            }
            setIsScheduleModalOpen(false);
            setEditingScheduleId(null);
            setNewSchedule({ name: '', interval: 'daily', cron_expression: '', scanner_type: 'wazuh' });
            fetchData();
        } catch (error: any) {
            console.error("Failed to save schedule:", error);
            alert(error.response?.data?.detail || "Failed to save schedule.");
        }
    };

    const handleEditSchedule = (schedule: ScanSchedule) => {
        setNewSchedule({
            name: schedule.name,
            interval: schedule.interval,
            cron_expression: schedule.cron_expression || '',
            scanner_type: schedule.scanner_type || 'wazuh',
        });
        setEditingScheduleId(schedule.id);
        setIsScheduleModalOpen(true);
    };

    const handleToggleSchedule = async (id: number) => {
        try {
            await api.patch(`/api/v1/scans/schedules/${id}`);
            fetchData();
        } catch (error: any) {
            console.error("Failed to toggle schedule:", error);
        }
    };

    const handleDeleteSchedule = async (id: number) => {
        if (!confirm("Delete this scan schedule?")) return;
        try {
            await api.delete(`/api/v1/scans/schedules/${id}`);
            fetchData();
        } catch (error: any) {
            console.error("Failed to delete schedule:", error);
        }
    };

    const toggleRunSelection = (idx: number) => {
        setSelectedRuns(prev => {
            const next = new Set(prev);
            if (next.has(idx)) next.delete(idx);
            else next.add(idx);
            return next;
        });
    };

    const toggleSelectAll = () => {
        if (selectedRuns.size === scanRuns.length) {
            setSelectedRuns(new Set());
        } else {
            setSelectedRuns(new Set(scanRuns.map((_, i) => i)));
        }
    };

    const handleDeleteSelected = async () => {
        if (selectedRuns.size === 0) return;
        const count = selectedRuns.size;
        if (!confirm(`Delete ${count} selected scan run(s)?`)) return;
        try {
            const ids = Array.from(selectedRuns).flatMap(idx => scanRuns[idx].scan_ids);
            const res = await api.post('/api/v1/scans/clear', { scan_ids: ids });
            alert(`Deleted ${res.data.deleted} scan records.`);
            setSelectedRuns(new Set());
            fetchData();
        } catch (error: any) {
            console.error("Failed to delete scans:", error);
            alert(error.response?.data?.detail || "Failed to delete scans.");
        }
    };

    const handleClearAll = async () => {
        if (!confirm("Delete ALL scan history?")) return;
        try {
            const res = await api.post('/api/v1/scans/clear', { all: true });
            alert(`Deleted ${res.data.deleted} scan records.`);
            setSelectedRuns(new Set());
            fetchData();
        } catch (error: any) {
            console.error("Failed to clear scans:", error);
            alert(error.response?.data?.detail || "Failed to clear scan history.");
        }
    };

    const getRunStatus = (run: ScanRunSummary) => {
        if (run.running > 0) return 'running';
        if (run.failed > 0 && run.completed === 0) return 'failed';
        if (run.failed > 0) return 'partial';
        return 'completed';
    };

    const getStatusBadge = (status: string) => {
        switch (status) {
            case 'completed':
                return <span className="inline-flex items-center rounded-md bg-green-100 text-green-700 px-2 py-1 text-xs font-medium">COMPLETED</span>;
            case 'running':
                return <span className="inline-flex items-center rounded-md bg-blue-100 text-blue-700 px-2 py-1 text-xs font-medium">RUNNING</span>;
            case 'failed':
                return <span className="inline-flex items-center rounded-md bg-red-100 text-red-700 px-2 py-1 text-xs font-medium">FAILED</span>;
            case 'partial':
                return <span className="inline-flex items-center rounded-md bg-yellow-100 text-yellow-700 px-2 py-1 text-xs font-medium">PARTIAL</span>;
            default:
                return <span className="inline-flex items-center rounded-md bg-gray-100 text-gray-600 px-2 py-1 text-xs font-medium">{status.toUpperCase()}</span>;
        }
    };

    return (
        <div className="max-w-7xl mx-auto">
            <div className="flex md:items-center md:justify-between mb-8">
                <div>
                    <h2 className="text-3xl font-bold leading-7 text-gray-900 font-mono">
                        Scan Jobs
                    </h2>
                    <p className="mt-1 text-sm text-gray-500 font-mono">Manage and monitor vulnerability scans</p>
                </div>
                <div className="mt-4 flex md:ml-4 md:mt-0 items-center gap-2">
                    <button
                        type="button"
                        onClick={handleSync}
                        className="inline-flex items-center gap-x-1.5 rounded-sm bg-white border border-gray-300 px-4 py-2 text-sm font-semibold text-gray-700 shadow-sm hover:bg-gray-50 font-mono"
                        title="Import latest Assets and Vulnerabilities from Wazuh database"
                    >
                        <ArrowPathIcon className="-ml-0.5 h-5 w-5" aria-hidden="true" />
                        Sync Data (Wazuh)
                    </button>
                    <button
                        type="button"
                        onClick={handleNessusSync}
                        disabled={nessusSyncing}
                        className="inline-flex items-center gap-x-1.5 rounded-sm bg-white border border-gray-300 px-4 py-2 text-sm font-semibold text-gray-700 shadow-sm hover:bg-gray-50 disabled:opacity-50 font-mono"
                        title="Import latest findings from Tenable Nessus (requires Settings → Nessus config)"
                    >
                        <ArrowPathIcon className={`-ml-0.5 h-5 w-5 ${nessusSyncing ? 'animate-spin' : ''}`} aria-hidden="true" />
                        {nessusSyncing ? 'Syncing…' : 'Sync Data (Nessus)'}
                    </button>
                    <button
                        type="button"
                        onClick={handleAutoscan}
                        className="inline-flex items-center gap-x-1.5 rounded-sm bg-vulncheck-blue px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 font-mono"
                        title="Trigger a new scan on all agents immediately"
                    >
                        <PlayIcon className="-ml-0.5 h-5 w-5" aria-hidden="true" />
                        Trigger New Scan
                    </button>
                </div>
            </div>

            {/* Scan Runs Summary Table */}
            <div className="bg-white border border-gray-200 shadow-sm rounded-sm overflow-hidden">
                {scanRuns.length > 0 && (
                    <div className="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
                        <span className="text-sm text-gray-500 font-mono">
                            {selectedRuns.size > 0
                                ? `${selectedRuns.size} of ${scanRuns.length} selected`
                                : `${scanRuns.length} scan runs`
                            }
                        </span>
                        <div className="flex items-center gap-2">
                            {selectedRuns.size > 0 && (
                                <button
                                    onClick={handleDeleteSelected}
                                    className="inline-flex items-center gap-1 text-xs font-medium text-red-600 hover:text-red-800 font-mono px-3 py-1.5 rounded hover:bg-red-50 border border-red-200"
                                >
                                    <TrashIcon className="h-3.5 w-3.5" />
                                    Delete Selected ({selectedRuns.size})
                                </button>
                            )}
                            <button
                                onClick={handleClearAll}
                                className="inline-flex items-center gap-1 text-xs font-medium text-gray-500 hover:text-gray-700 font-mono px-2 py-1 rounded hover:bg-gray-100"
                            >
                                <TrashIcon className="h-3.5 w-3.5" />
                                Clear All
                            </button>
                        </div>
                    </div>
                )}
                <div className="overflow-x-auto max-h-[600px] overflow-y-auto">
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                            <tr>
                                <th scope="col" className="px-4 py-3 w-10">
                                    <input
                                        type="checkbox"
                                        checked={scanRuns.length > 0 && selectedRuns.size === scanRuns.length}
                                        onChange={toggleSelectAll}
                                        className="h-4 w-4 rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue"
                                    />
                                </th>
                                <th scope="col" className="px-4 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider w-8"></th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Started</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Type</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Assets</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Vulns Found</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-mono font-medium text-gray-500 uppercase tracking-wider">Duration</th>
                            </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200 font-mono text-sm">
                            {scanRuns.map((run, idx) => {
                                const runStatus = getRunStatus(run);
                                const hasFailed = run.failed > 0;
                                const isExpanded = expandedRun === idx;
                                const duration = run.completed_at
                                    ? Math.round((new Date(run.completed_at).getTime() - new Date(run.started_at).getTime()) / 1000)
                                    : null;

                                return (
                                    <Fragment key={idx}>
                                        <tr
                                            className={`${hasFailed ? 'cursor-pointer' : ''} hover:bg-gray-50`}
                                        >
                                            <td className="px-4 py-4" onClick={(e) => e.stopPropagation()}>
                                                <input
                                                    type="checkbox"
                                                    checked={selectedRuns.has(idx)}
                                                    onChange={() => toggleRunSelection(idx)}
                                                    className="h-4 w-4 rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue"
                                                />
                                            </td>
                                            <td className="px-4 py-4 text-gray-400" onClick={() => hasFailed && setExpandedRun(isExpanded ? null : idx)}>
                                                {hasFailed ? (
                                                    isExpanded
                                                        ? <ChevronDownIcon className="h-4 w-4" />
                                                        : <ChevronRightIcon className="h-4 w-4" />
                                                ) : null}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-gray-900">
                                                {new Date(run.started_at).toLocaleString()}
                                            </td>
                                            <td className="px-6 py-4 text-gray-500 capitalize">{run.scan_type}</td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                {getStatusBadge(runStatus)}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <span className="text-gray-900 font-bold">{run.completed}</span>
                                                <span className="text-gray-400">/{run.total_assets}</span>
                                                {run.failed > 0 && (
                                                    <span className="ml-2 text-red-600 text-xs font-medium">
                                                        ({run.failed} failed)
                                                    </span>
                                                )}
                                            </td>
                                            <td className="px-6 py-4 text-center font-bold text-gray-900">
                                                {run.total_vulns_found}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-gray-500">
                                                {duration !== null ? (
                                                    duration < 60 ? `${duration}s` : `${Math.floor(duration / 60)}m ${duration % 60}s`
                                                ) : (
                                                    runStatus === 'running' ? <span className="text-blue-600">in progress...</span> : '-'
                                                )}
                                            </td>
                                        </tr>
                                        {isExpanded && hasFailed && (
                                            <tr>
                                                <td colSpan={8} className="px-8 py-3 bg-red-50 border-l-4 border-red-400">
                                                    <p className="text-xs font-medium text-red-800 mb-2">Failed Assets:</p>
                                                    <div className="space-y-1">
                                                        {run.failed_assets.map((fa, fi) => (
                                                            <div key={fi} className="flex items-start gap-2 text-xs">
                                                                <span className="font-medium text-red-700 min-w-[140px]">{fa.asset_hostname}</span>
                                                                <span className="text-red-600 break-all">{fa.error_message}</span>
                                                            </div>
                                                        ))}
                                                    </div>
                                                </td>
                                            </tr>
                                        )}
                                    </Fragment>
                                );
                            })}
                            {scanRuns.length === 0 && !loading && (
                                <tr><td colSpan={8} className="text-center py-8 text-gray-500">No scan runs found.</td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Scheduled Scans Section */}
            <div className="mt-8 bg-white border border-gray-200 shadow-sm rounded-sm overflow-hidden">
                <div className="p-6 border-b border-gray-200 flex justify-between items-center bg-gray-50/50">
                    <div className="flex items-center gap-2">
                        <ClockIcon className="h-5 w-5 text-gray-500" />
                        <h3 className="text-lg font-bold text-gray-900 font-mono">Automatic Scan Schedules</h3>
                    </div>
                    <button
                        type="button"
                        onClick={() => setIsScheduleModalOpen(true)}
                        className="inline-flex items-center gap-x-1.5 rounded-sm bg-vulncheck-blue px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 font-mono"
                    >
                        + New Schedule
                    </button>
                </div>
                {schedules.length === 0 ? (
                    <div className="p-8 text-center text-gray-500 font-mono text-sm">
                        No automatic scan schedules configured. Create one to scan assets automatically.
                    </div>
                ) : (
                    <div className="divide-y divide-gray-200">
                        {schedules.map((schedule) => (
                            <div key={schedule.id} className="px-6 py-4 flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                    <div className={`w-2.5 h-2.5 rounded-full ${schedule.enabled ? 'bg-green-500' : 'bg-gray-300'}`} />
                                    <div>
                                        <div className="flex items-center gap-2">
                                            <p className="font-medium text-gray-900 font-mono">{schedule.name}</p>
                                            <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
                                                schedule.scanner_type === 'nessus'
                                                    ? 'bg-purple-100 text-purple-700'
                                                    : 'bg-green-100 text-green-700'
                                            }`}>
                                                {schedule.scanner_type === 'nessus' ? 'NESSUS' : 'WAZUH'}
                                            </span>
                                        </div>
                                        <p className="text-xs text-gray-500 font-mono">
                                            {schedule.interval === 'cron' ? `Cron: ${schedule.cron_expression}` : (INTERVAL_LABELS[schedule.interval] || schedule.interval)}
                                            {schedule.last_run && ` · Last run: ${new Date(schedule.last_run).toLocaleString()}`}
                                            {schedule.next_run && schedule.enabled && ` · Next: ${new Date(schedule.next_run).toLocaleString()}`}
                                        </p>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => handleToggleSchedule(schedule.id)}
                                        className={`px-3 py-1 text-xs font-medium rounded-md font-mono ${schedule.enabled
                                            ? 'bg-yellow-50 text-yellow-700 ring-1 ring-yellow-600/20 hover:bg-yellow-100'
                                            : 'bg-green-50 text-green-700 ring-1 ring-green-600/20 hover:bg-green-100'
                                            }`}
                                    >
                                        {schedule.enabled ? 'Disable' : 'Enable'}
                                    </button>
                                    <button
                                        onClick={() => handleEditSchedule(schedule)}
                                        className="p-1 text-gray-400 hover:text-vulncheck-blue transition-colors"
                                        title="Edit Schedule"
                                    >
                                        <PencilIcon className="h-4 w-4" />
                                    </button>
                                    <button
                                        onClick={() => handleDeleteSchedule(schedule.id)}
                                        className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                                    >
                                        <TrashIcon className="h-4 w-4" />
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>

            {/* Autoscan Progress/Result Modal */}
            {isScheduleModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-500 bg-opacity-75">
                    <div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
                        <h3 className="text-lg font-bold mb-4 font-mono">{editingScheduleId ? 'Edit Scan Schedule' : 'Create Automatic Scan Schedule'}</h3>
                        <form onSubmit={handleCreateSchedule} className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 font-mono">Schedule Name</label>
                                <input
                                    type="text"
                                    required
                                    value={newSchedule.name}
                                    onChange={(e) => setNewSchedule({ ...newSchedule, name: e.target.value })}
                                    placeholder="e.g. Nightly Full Scan"
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 font-mono">Scan Interval</label>
                                <select
                                    value={newSchedule.interval}
                                    onChange={(e) => setNewSchedule({ ...newSchedule, interval: e.target.value })}
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                >
                                    <option value="every_hour">Every Hour</option>
                                    <option value="every_6_hours">Every 6 Hours</option>
                                    <option value="every_12_hours">Every 12 Hours</option>
                                    <option value="daily">Daily</option>
                                    <option value="weekly">Weekly</option>
                                    <option value="cron">Custom Cron (Expert)</option>
                                </select>
                            </div>
                            {newSchedule.interval === 'cron' && (
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 font-mono">Cron Expression</label>
                                    <input
                                        type="text"
                                        required
                                        value={newSchedule.cron_expression}
                                        onChange={(e) => setNewSchedule({ ...newSchedule, cron_expression: e.target.value })}
                                        placeholder="* * * * * (min hour day month weekday)"
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                    />
                                    <p className="mt-1 text-[10px] text-gray-500 font-mono">
                                        Example: "30 14 * * *" for 14:30 daily.
                                    </p>
                                </div>
                            )}
                            <div>
                                <label className="block text-sm font-medium text-gray-700 font-mono">Scanner</label>
                                <select
                                    value={newSchedule.scanner_type}
                                    onChange={(e) => setNewSchedule({ ...newSchedule, scanner_type: e.target.value })}
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm font-mono"
                                >
                                    <option value="wazuh">Wazuh (agent-based)</option>
                                    <option value="nessus">Tenable Nessus (network scan + import)</option>
                                </select>
                                {newSchedule.scanner_type === 'nessus' && (
                                    <p className="mt-1 text-[11px] text-amber-700 font-mono bg-amber-50 border border-amber-200 rounded px-2 py-1">
                                        Nessus must be configured in Settings → Tenable Nessus. Uses default_scan_ids from config.
                                    </p>
                                )}
                            </div>
                            <p className="text-xs text-gray-500 font-mono">
                                {newSchedule.scanner_type === 'nessus'
                                    ? 'Automatically imports Nessus findings at the selected interval.'
                                    : 'Automatically scans all Wazuh-connected assets at the selected interval.'}
                            </p>
                            <div className="flex justify-end gap-2 mt-6">
                                <button type="button" onClick={() => {
                                    setIsScheduleModalOpen(false);
                                    setEditingScheduleId(null);
                                    setNewSchedule({ name: '', interval: 'daily', cron_expression: '', scanner_type: 'wazuh' });
                                }} className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 font-mono">Cancel</button>
                                <button type="submit" className="px-4 py-2 text-sm font-medium text-white bg-vulncheck-blue rounded-md hover:bg-blue-600">
                                    {editingScheduleId ? 'Save Changes' : 'Create Schedule'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Autoscan Progress/Result Modal */}
            {isAutoscanModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-500 bg-opacity-75">
                    <div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6 text-center">
                        <h3 className="text-lg font-bold mb-4 font-mono">Wazuh Autoscan</h3>

                        {autoscanStatus === 'running' && (
                            <div className="py-8">
                                <ArrowPathIcon className="h-12 w-12 text-vulncheck-blue animate-spin mx-auto mb-4" />
                                <p className="text-gray-600 font-mono">Initiating scans on all connected agents...</p>
                                <p className="text-xs text-gray-400 mt-2 font-mono">This may take a few moments.</p>
                            </div>
                        )}

                        {autoscanStatus === 'complete' && autoscanResult && (
                            <div className="py-4">
                                <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 mb-4">
                                    <svg className="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" aria-hidden="true">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                                    </svg>
                                </div>
                                <h4 className="text-base font-semibold leading-6 text-gray-900 font-mono">Scan Initiated Successfully</h4>
                                <div className="mt-2">
                                    <p className="text-sm text-gray-500 font-mono">{autoscanResult.message}</p>
                                    <p className="text-sm font-bold text-gray-900 mt-2 font-mono">Triggered: {autoscanResult.scans_triggered}</p>
                                </div>
                                {autoscanResult.errors && autoscanResult.errors.length > 0 && (
                                    <div className="mt-4 text-left bg-red-50 p-3 rounded-md border border-red-100">
                                        <p className="text-xs font-bold text-red-800 mb-1 font-mono">Errors ({autoscanResult.errors.length}):</p>
                                        <ul className="text-xs text-red-700 list-disc pl-4 font-mono">
                                            {autoscanResult.errors.map((err, i) => (
                                                <li key={i}>{err}</li>
                                            ))}
                                        </ul>
                                    </div>
                                )}
                                <div className="mt-6">
                                    <button
                                        type="button"
                                        className="inline-flex w-full justify-center rounded-md bg-vulncheck-blue px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 font-mono"
                                        onClick={() => setIsAutoscanModalOpen(false)}
                                    >
                                        Close
                                    </button>
                                </div>
                            </div>
                        )}

                        {autoscanStatus === 'error' && autoscanResult && (
                            <div className="py-4">
                                <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-red-100 mb-4">
                                    <svg className="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                                    </svg>
                                </div>
                                <h4 className="text-base font-semibold leading-6 text-gray-900 font-mono">Scan Failed</h4>
                                <div className="mt-2">
                                    <p className="text-sm text-gray-500 font-mono">{autoscanResult.message}</p>
                                </div>
                                <div className="mt-6">
                                    <button
                                        type="button"
                                        className="inline-flex w-full justify-center rounded-md bg-gray-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-gray-500 font-mono"
                                        onClick={() => setIsAutoscanModalOpen(false)}
                                    >
                                        Close
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* Toast Notification */}
            {toast && (
                <div className={`fixed bottom-6 right-6 z-50 flex items-center gap-3 px-6 py-4 rounded-lg shadow-lg font-mono text-sm transition-all duration-300 ${toast.type === 'success' ? 'bg-green-600 text-white' :
                    toast.type === 'error' ? 'bg-red-600 text-white' :
                        'bg-blue-600 text-white'
                    }`}>
                    {toast.type === 'success' && <span className="text-lg">✅</span>}
                    {toast.type === 'error' && <span className="text-lg">❌</span>}
                    {toast.type === 'info' && <span className="text-lg">ℹ️</span>}
                    <span>{toast.message}</span>
                    <button onClick={() => setToast(null)} className="ml-2 hover:opacity-75">×</button>
                </div>
            )}

            {/* Sync Progress/Result Modal */}
            {isSyncModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-500 bg-opacity-75">
                    <div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6 text-center">
                        <h3 className="text-lg font-bold mb-4 font-mono">Synchronize Data</h3>

                        {syncStatus === 'running' && (
                            <div className="py-8">
                                <ArrowPathIcon className="h-12 w-12 text-blue-500 animate-spin mx-auto mb-4" />
                                <p className="text-gray-900 font-bold font-mono text-lg mb-2">Syncing...</p>
                                <div className="space-y-2">
                                    <div className={`flex items-center justify-center gap-2 ${syncStep === 'assets' ? 'text-blue-600 font-bold' : 'text-gray-400'}`}>
                                        {syncStep === 'assets' && <ArrowPathIcon className="h-4 w-4 animate-spin" />}
                                        <span className="font-mono text-sm">1. Importing Assets</span>
                                    </div>
                                    <div className={`flex items-center justify-center gap-2 ${syncStep === 'vulns' ? 'text-blue-600 font-bold' : 'text-gray-400'}`}>
                                        {syncStep === 'vulns' && <ArrowPathIcon className="h-4 w-4 animate-spin" />}
                                        <span className="font-mono text-sm">2. Syncing Vulnerabilities</span>
                                    </div>
                                </div>
                            </div>
                        )}

                        {syncStatus === 'complete' && syncResult && (
                            <div className="py-4">
                                <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 mb-4">
                                    <svg className="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                                    </svg>
                                </div>
                                <h4 className="text-base font-semibold leading-6 text-gray-900 font-mono">Synchronization Complete</h4>
                                <div className="mt-4 text-sm font-mono text-left bg-gray-50 p-4 rounded-md">
                                    <p><strong>Assets:</strong> {syncResult.assetsCreated} created, {syncResult.assetsUpdated} updated</p>
                                    <p className="mt-2"><strong>Vulnerabilities:</strong> {syncResult.vulnMessage}</p>
                                </div>
                                <div className="mt-6">
                                    <button
                                        type="button"
                                        className="inline-flex w-full justify-center rounded-md bg-vulncheck-blue px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 font-mono"
                                        onClick={() => setIsSyncModalOpen(false)}
                                    >
                                        Close
                                    </button>
                                </div>
                            </div>
                        )}

                        {syncStatus === 'error' && (
                            <div className="py-4">
                                <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-red-100 mb-4">
                                    <svg className="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                                    </svg>
                                </div>
                                <h4 className="text-base font-semibold leading-6 text-gray-900 font-mono">Sync Failed</h4>
                                <p className="text-sm text-gray-500 mt-2 font-mono">Check the logs or try again later.</p>
                                <div className="mt-6">
                                    <button
                                        type="button"
                                        className="inline-flex w-full justify-center rounded-md bg-gray-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-gray-500 font-mono"
                                        onClick={() => setIsSyncModalOpen(false)}
                                    >
                                        Close
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}
