"use client";

import { useState, useEffect } from 'react';
import api from '../../lib/api';
import MfaCard from '../../components/auth/MfaCard';

interface User {
    id: number;
    username: string;
    email: string;
    role: string;
    is_active: boolean;
    failed_login_attempts: number;
}

export default function SettingsPage() {
    const [newUser, setNewUser] = useState({ username: '', email: '', password: '', role: 'readonly' });
    const [creationStatus, setCreationStatus] = useState({ message: '', type: '' });
    const [userRole, setUserRole] = useState('');
    const [currentUserInfo, setCurrentUserInfo] = useState<{ username: string; email: string; role: string } | null>(null);

    const [users, setUsers] = useState<User[]>([]);
    const [loadingUsers, setLoadingUsers] = useState(false);

    const fetchUsers = async () => {
        setLoadingUsers(true);
        try {
            const response = await api.get('/auth/users');
            setUsers(response.data);
        } catch (error) {
            console.error("Failed to fetch users", error);
        } finally {
            setLoadingUsers(false);
        }
    };

    const handleCreateUser = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            await api.post('/auth/register', newUser);
            setCreationStatus({ message: 'User created successfully', type: 'success' });
            setNewUser({ username: '', email: '', password: '', role: 'readonly' });
            fetchUsers(); // Refresh list
        } catch (error: any) {
            console.error("Create User Error:", error);
            const detail = error.response?.data?.detail;
            const message = typeof detail === 'string' ? detail : (detail ? JSON.stringify(detail) : 'Failed to create user (Check Console)');
            setCreationStatus({ message: message, type: 'error' });
        }
    };

    const [wazuhConfig, setWazuhConfig] = useState({
        api_url: 'https://wazuh.local:55000',
        username: 'wazuh',
        password: '',
        indexer_url: 'https://wazuh.local:9200',
        indexer_username: 'admin',
        indexer_password: ''
    });
    const [nessusConfig, setNessusConfig] = useState({
        base_url: 'https://nessus.local:8834',
        access_key: '',
        secret_key: '',
        verify_ssl: true,
        default_scan_ids: '' as string,   // comma-separated in UI, parsed on save
        auto_create_assets: false,
    });
    const [nessusConfigured, setNessusConfigured] = useState(false);
    const [isNessusModalOpen, setIsNessusModalOpen] = useState(false);
    const [nessusTestStatus, setNessusTestStatus] = useState<{ message: string; type: string }>({ message: '', type: '' });
    const [nessusSyncStatus, setNessusSyncStatus] = useState<{ message: string; type: string }>({ message: '', type: '' });
    const [nessusSyncing, setNessusSyncing] = useState(false);
    const [aiConfig, setAiConfig] = useState({
        provider: 'infomaniak',
        product_id: '',
        api_token: '',
        model: 'llama3',
        base_url: ''
    });
    const [smtpConfig, setSmtpConfig] = useState({ host: '', port: '587', username: '', password: '', from_address: '', use_tls: true });
    const [emailTemplate, setEmailTemplate] = useState({ subject: '', body: '' });
    const [newVulnTemplate, setNewVulnTemplate] = useState({ subject: '', body: '' });
    const [notificationMinSeverity, setNotificationMinSeverity] = useState<'critical' | 'high' | 'medium' | 'low'>('critical');
    const [notificationMode, setNotificationMode] = useState<'digest' | 'single'>('digest');
    const [notificationSavingStatus, setNotificationSavingStatus] = useState({ message: '', type: '' });
    // MFA enforcement (Settings → Security card)
    const [mfaEnforced, setMfaEnforced] = useState(false);
    const [mfaEnforcedRoles, setMfaEnforcedRoles] = useState<string[]>(['admin', 'editor']);
    const [mfaEnforceSso, setMfaEnforceSso] = useState(false);
    const [mfaSavingStatus, setMfaSavingStatus] = useState({ message: '', type: '' });
    const [smtpConfigured, setSmtpConfigured] = useState(false);
    const [isSmtpModalOpen, setIsSmtpModalOpen] = useState(false);
    const [isTemplateModalOpen, setIsTemplateModalOpen] = useState(false);
    const [isNewVulnTemplateModalOpen, setIsNewVulnTemplateModalOpen] = useState(false);
    const [isPreviewOpen, setIsPreviewOpen] = useState(false);
    const [previewHtml, setPreviewHtml] = useState('');
    const [testEmail, setTestEmail] = useState('');
    const [testEmailStatus, setTestEmailStatus] = useState({ message: '', type: '' });
    const [configStatus, setConfigStatus] = useState({ message: '', type: '' });

    // UI State
    const [isWazuhModalOpen, setIsWazuhModalOpen] = useState(false);
    const [isAIModalOpen, setIsAIModalOpen] = useState(false);
    const [aiConfigured, setAiConfigured] = useState(false);
    const [wazuhConfigured, setWazuhConfigured] = useState(false);

    // Password Reset State
    const [resetUser, setResetUser] = useState<User | null>(null);
    const [resetPassword, setResetPassword] = useState('');
    const [resetStatus, setResetStatus] = useState({ message: '', type: '' });

    // Edit User State
    const [editUser, setEditUser] = useState<User | null>(null);
    const [isEditUserModalOpen, setIsEditUserModalOpen] = useState(false);
    const [editFormData, setEditFormData] = useState({ email: '', role: '' });

    // Delete User State
    const [deleteUser, setDeleteUser] = useState<User | null>(null);
    const [deleteStatus, setDeleteStatus] = useState({ message: '', type: '' });

    const handleResetPassword = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!resetUser) return;

        try {
            await api.post(`/auth/users/${resetUser.id}/reset-password`, { new_password: resetPassword });
            setResetStatus({ message: 'Password reset successfully', type: 'success' });
            setTimeout(() => {
                setResetUser(null);
                setResetPassword('');
                setResetStatus({ message: '', type: '' });
            }, 1500);
        } catch (error: any) {
            setResetStatus({ message: error.response?.data?.detail || 'Failed to reset password', type: 'error' });
        }
    };

    const handleEditUser = (user: User) => {
        setEditUser(user);
        setEditFormData({ email: user.email, role: user.role });
        setIsEditUserModalOpen(true);
    };

    const handleUpdateUser = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!editUser) return;

        try {
            await api.patch(`/auth/users/${editUser.id}`, editFormData);
            setCreationStatus({ message: 'User updated successfully', type: 'success' });
            setIsEditUserModalOpen(false);
            setEditUser(null);
            fetchUsers();
        } catch (error: any) {
            setCreationStatus({ message: error.response?.data?.detail || 'Failed to update user', type: 'error' });
        }
    };

    const handleDeleteUser = async () => {
        if (!deleteUser) return;
        try {
            await api.delete(`/auth/users/${deleteUser.id}`);
            setDeleteUser(null);
            setDeleteStatus({ message: '', type: '' });
            fetchUsers();
        } catch (error: any) {
            setDeleteStatus({ message: error.response?.data?.detail || 'Failed to delete user', type: 'error' });
        }
    };

    const fetchSettings = async () => {
        try {
            const [wazuhRes, aiRes, smtpRes, templateRes, newVulnTemplateRes, notifMinSevRes, notifModeRes, nessusRes, mfaEnfRes, mfaRolesRes, mfaSsoRes] = await Promise.all([
                api.get('/api/v1/settings/wazuh_config').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/ai_config').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/smtp_config').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/email_template_sla_breach').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/email_template_new_vuln').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/notification_min_severity').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/notification_mode').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/nessus_config').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/mfa_enforced').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/mfa_enforced_roles').catch(() => ({ data: { value: null } })),
                api.get('/api/v1/settings/mfa_enforce_sso_users').catch(() => ({ data: { value: null } })),
            ]);

            if (wazuhRes.data.value) {
                const parsed = JSON.parse(wazuhRes.data.value);
                setWazuhConfig({ ...wazuhConfig, ...parsed });
                setWazuhConfigured(true);
            }
            if (aiRes.data.value) {
                const parsed = JSON.parse(aiRes.data.value);
                setAiConfig({
                    provider: parsed.provider || 'infomaniak',
                    product_id: parsed.product_id || '',
                    api_token: parsed.api_token || parsed.api_key || '',
                    model: parsed.model || 'llama3',
                    base_url: parsed.base_url || ''
                });
                setAiConfigured(true);
            }
            if (smtpRes.data.value) {
                const parsed = JSON.parse(smtpRes.data.value);
                setSmtpConfig({ ...smtpConfig, ...parsed });
                setSmtpConfigured(true);
            }
            if (templateRes.data.value) {
                const parsed = JSON.parse(templateRes.data.value);
                setEmailTemplate(parsed);
            }
            if (newVulnTemplateRes.data.value) {
                const parsed = JSON.parse(newVulnTemplateRes.data.value);
                setNewVulnTemplate(parsed);
            }
            if (notifMinSevRes.data.value) {
                const val = String(notifMinSevRes.data.value).toLowerCase();
                if (val === 'critical' || val === 'high' || val === 'medium' || val === 'low') {
                    setNotificationMinSeverity(val);
                }
            }
            if (notifModeRes.data.value) {
                const val = String(notifModeRes.data.value).toLowerCase();
                if (val === 'digest' || val === 'single') {
                    setNotificationMode(val);
                }
            }
            // MFA enforcement
            if (mfaEnfRes.data.value != null) {
                setMfaEnforced(String(mfaEnfRes.data.value).toLowerCase() === 'true');
            }
            if (mfaRolesRes.data.value) {
                try {
                    const raw = mfaRolesRes.data.value;
                    const parsed = typeof raw === 'string' && raw.trim().startsWith('[')
                        ? JSON.parse(raw)
                        : String(raw).split(',').map((s: string) => s.trim()).filter(Boolean);
                    if (Array.isArray(parsed)) setMfaEnforcedRoles(parsed.map(String));
                } catch { /* ignore */ }
            }
            if (mfaSsoRes.data.value != null) {
                setMfaEnforceSso(String(mfaSsoRes.data.value).toLowerCase() === 'true');
            }
            if (nessusRes.data.value) {
                try {
                    const parsed = JSON.parse(nessusRes.data.value);
                    setNessusConfig({
                        base_url: parsed.base_url || '',
                        access_key: parsed.access_key || '',
                        secret_key: parsed.secret_key || '',
                        verify_ssl: parsed.verify_ssl !== false,
                        default_scan_ids: Array.isArray(parsed.default_scan_ids)
                            ? parsed.default_scan_ids.join(',')
                            : '',
                        auto_create_assets: !!parsed.auto_create_assets,
                    });
                    setNessusConfigured(!!parsed.base_url && !!parsed.access_key);
                } catch { /* ignore malformed */ }
            }
        } catch (error) {
            console.error("Failed to fetch settings", error);
        }
    };

    const handleSaveNotificationMinSeverity = async (newValue: 'critical' | 'high' | 'medium' | 'low') => {
        setNotificationMinSeverity(newValue);
        setNotificationSavingStatus({ message: 'Saving...', type: 'loading' });
        try {
            await api.put('/api/v1/settings/notification_min_severity', { value: newValue });
            setNotificationSavingStatus({ message: 'Saved.', type: 'success' });
            setTimeout(() => setNotificationSavingStatus({ message: '', type: '' }), 2000);
        } catch (error: any) {
            console.error("Failed to save notification threshold", error);
            setNotificationSavingStatus({ message: error.response?.data?.detail || 'Failed to save', type: 'error' });
        }
    };

    const handleSaveNessusConfig = async () => {
        setConfigStatus({ message: 'Saving Nessus config...', type: 'loading' });
        try {
            const scan_ids: number[] = nessusConfig.default_scan_ids
                .split(',')
                .map(s => parseInt(s.trim(), 10))
                .filter(n => Number.isFinite(n) && n > 0);
            const payload = {
                base_url: nessusConfig.base_url.trim(),
                access_key: nessusConfig.access_key.trim(),
                secret_key: nessusConfig.secret_key.trim(),
                verify_ssl: nessusConfig.verify_ssl,
                default_scan_ids: scan_ids,
                auto_create_assets: nessusConfig.auto_create_assets,
            };
            await api.put('/api/v1/settings/nessus_config', { value: JSON.stringify(payload) });
            setNessusConfigured(!!payload.base_url && !!payload.access_key);
            setConfigStatus({ message: 'Nessus configuration saved.', type: 'success' });
            setTimeout(() => setConfigStatus({ message: '', type: '' }), 3000);
        } catch (e: any) {
            setConfigStatus({ message: e?.response?.data?.detail || 'Save failed', type: 'error' });
        }
    };

    const handleTestNessus = async () => {
        setNessusTestStatus({ message: 'Testing…', type: 'loading' });
        try {
            const res = await api.post('/api/v1/vulnerabilities/nessus/test');
            if (res.data?.ok) {
                setNessusTestStatus({
                    message: `OK — server ${res.data.server_version || '?'}, ${res.data.scans_visible} scans visible.`,
                    type: 'success',
                });
            } else {
                setNessusTestStatus({
                    message: `Failed (${res.data?.step || 'unknown'}): ${res.data?.error || 'no detail'}`,
                    type: 'error',
                });
            }
        } catch (e: any) {
            setNessusTestStatus({ message: e?.response?.data?.detail || 'Test request failed', type: 'error' });
        }
    };

    const handleNessusSyncNow = async () => {
        if (nessusSyncing) return;
        if (!confirm('Trigger Nessus sync now? Imports findings from configured scans into VulnCheck.')) return;
        setNessusSyncing(true);
        setNessusSyncStatus({ message: 'Syncing…', type: 'loading' });
        try {
            const res = await api.post('/api/v1/vulnerabilities/nessus/sync', {});
            const s = res.data || {};
            setNessusSyncStatus({
                message: `Done: ${s.vulns_created || 0} created, ${s.vulns_merged || 0} merged, ${s.hosts_synced || 0} hosts, ${(s.unmatched_hosts || []).length} unmatched.`,
                type: 'success',
            });
        } catch (e: any) {
            setNessusSyncStatus({ message: e?.response?.data?.detail || 'Sync failed', type: 'error' });
        } finally {
            setNessusSyncing(false);
        }
    };

    const handleSaveMfaEnforcement = async (
        next: { enforced?: boolean; roles?: string[]; enforceSso?: boolean }
    ) => {
        const enforced = next.enforced ?? mfaEnforced;
        const roles = next.roles ?? mfaEnforcedRoles;
        const enforceSso = next.enforceSso ?? mfaEnforceSso;
        setMfaEnforced(enforced);
        setMfaEnforcedRoles(roles);
        setMfaEnforceSso(enforceSso);
        setMfaSavingStatus({ message: 'Saving…', type: 'loading' });
        try {
            await Promise.all([
                api.put('/api/v1/settings/mfa_enforced', { value: enforced ? 'true' : 'false' }),
                api.put('/api/v1/settings/mfa_enforced_roles', { value: JSON.stringify(roles) }),
                api.put('/api/v1/settings/mfa_enforce_sso_users', { value: enforceSso ? 'true' : 'false' }),
            ]);
            setMfaSavingStatus({ message: 'Saved.', type: 'success' });
            setTimeout(() => setMfaSavingStatus({ message: '', type: '' }), 2000);
        } catch (e: any) {
            setMfaSavingStatus({ message: e?.response?.data?.detail || 'Save failed', type: 'error' });
        }
    };

    const handleSaveNotificationMode = async (newValue: 'digest' | 'single') => {
        setNotificationMode(newValue);
        setNotificationSavingStatus({ message: 'Saving...', type: 'loading' });
        try {
            await api.put('/api/v1/settings/notification_mode', { value: newValue });
            setNotificationSavingStatus({ message: 'Saved.', type: 'success' });
            setTimeout(() => setNotificationSavingStatus({ message: '', type: '' }), 2000);
        } catch (error: any) {
            console.error("Failed to save notification mode", error);
            setNotificationSavingStatus({ message: error.response?.data?.detail || 'Failed to save', type: 'error' });
        }
    };

    useEffect(() => {
        api.get('/auth/me')
            .then((res) => {
                const me = res.data || {};
                setUserRole(me.role || '');
                setCurrentUserInfo({ username: me.username || '', email: me.email || '', role: me.role || '' });
                if (me.role === 'admin') {
                    fetchSettings();
                }
            })
            .catch(() => null);
        fetchUsers();
    }, []);

    const handleSaveWazuhConfig = async () => {
        try {
            await api.put('/api/v1/settings/wazuh_config', { value: JSON.stringify(wazuhConfig) });
            setWazuhConfigured(true);
            setConfigStatus({ message: 'Wazuh configuration saved.', type: 'success' });
            setTimeout(() => setIsWazuhModalOpen(false), 1000);
        } catch (error: any) {
            console.error("Failed to save Wazuh config", error);
            setConfigStatus({ message: error.response?.data?.detail || 'Failed to save configuration.', type: 'error' });
        }
    };

    const handleSaveAIConfig = async () => {
        try {
            await api.put('/api/v1/settings/ai_config', { value: JSON.stringify(aiConfig) });
            setAiConfigured(true);
            setConfigStatus({ message: 'AI configuration saved.', type: 'success' });
            setTimeout(() => setIsAIModalOpen(false), 1000);
        } catch (error: any) {
            console.error("Failed to save AI config", error);
            setConfigStatus({ message: error.response?.data?.detail || 'Failed to save configuration.', type: 'error' });
        }
    };

    const handleSaveSmtpConfig = async () => {
        try {
            await api.put('/api/v1/settings/smtp_config', { value: JSON.stringify(smtpConfig) });
            setSmtpConfigured(true);
            setConfigStatus({ message: 'SMTP configuration saved.', type: 'success' });
            setTimeout(() => setIsSmtpModalOpen(false), 1000);
        } catch (error: any) {
            console.error("Failed to save SMTP config", error);
            setConfigStatus({ message: error.response?.data?.detail || 'Failed to save configuration.', type: 'error' });
        }
    };

    const handleTestConnection = async () => {
        if (!testEmail) {
            setTestEmailStatus({ message: 'Please enter a recipient email.', type: 'error' });
            return;
        }
        setTestEmailStatus({ message: 'Sending test email...', type: 'info' });
        try {
            await api.post('/api/v1/notifications/test', {
                to_email: testEmail,
                smtp_config: smtpConfig
            });
            setTestEmailStatus({ message: 'Test email sent successfully!', type: 'success' });
        } catch (error: any) {
            console.error("Failed to send test email", error);
            setTestEmailStatus({ message: error.response?.data?.detail || 'Failed to send test email.', type: 'error' });
        }
    };

    const handleSaveEmailTemplate = async () => {
        try {
            await api.put('/api/v1/settings/email_template_sla_breach', { value: JSON.stringify(emailTemplate) });
            setConfigStatus({ message: 'Email template saved.', type: 'success' });
            setTimeout(() => setIsTemplateModalOpen(false), 1000);
        } catch (error: any) {
            console.error("Failed to save email template", error);
            setConfigStatus({ message: error.response?.data?.detail || 'Failed to save template.', type: 'error' });
        }
    };

    const handleSaveNewVulnTemplate = async () => {
        try {
            await api.put('/api/v1/settings/email_template_new_vuln', { value: JSON.stringify(newVulnTemplate) });
            setConfigStatus({ message: 'New vulnerability template saved.', type: 'success' });
            setTimeout(() => setIsNewVulnTemplateModalOpen(false), 1000);
        } catch (error: any) {
            console.error("Failed to save new vuln template", error);
            setConfigStatus({ message: error.response?.data?.detail || 'Failed to save template.', type: 'error' });
        }
    };

    const PREVIEW_SAMPLE_DATA: Record<string, string> = {
        cve_id: 'CVE-2024-1234',
        severity: 'high',
        severity_upper: 'HIGH',
        cvss_score: '7.5',
        asset_hostname: 'webserver-01',
        asset_ip: '10.10.66.30',
        package_name: 'openssl-3.0.2',
        title: 'Remote Code Execution in OpenSSL',
        description: 'A buffer overflow vulnerability in OpenSSL allows remote attackers to execute arbitrary code via crafted network packets. This affects all versions prior to 3.0.3.',
        detected_at: '2026-01-27 20:38 UTC',
        dashboard_url: 'https://vulncheck.local/vulnerabilities',
        hours_overdue: '48',
        assigned_user: 'admin',
        recipient_name: 'Admin User',
        recipient_email: 'admin@vulncheck.local',
    };

    const renderPreview = (template: { subject: string; body: string }) => {
        if (!template.body) {
            setPreviewHtml('<html><body style="font-family: Arial, sans-serif; padding: 40px; text-align: center; color: #6b7280;"><h2>No custom template configured</h2><p>The default template from the backend will be used. Edit the template first to preview it.</p></body></html>');
            setIsPreviewOpen(true);
            return;
        }
        let rendered = template.body;
        for (const [key, value] of Object.entries(PREVIEW_SAMPLE_DATA)) {
            rendered = rendered.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
        }
        setPreviewHtml(rendered);
        setIsPreviewOpen(true);
    };

    return (
        <div className="max-w-7xl mx-auto">
            <div className="mb-8">
                <h2 className="text-3xl font-bold leading-7 text-gray-900 font-mono">
                    System Settings
                </h2>
            </div>

            <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
                {/* General Settings */}
                <div className="lg:col-span-2">
                    {userRole === 'admin' && (
                    <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-6 mb-6">
                        <h3 className="text-lg font-bold text-gray-900 font-mono mb-4 border-b border-gray-100 pb-2">
                            General Configuration
                        </h3>
                        <form className="space-y-6">
                            <div>
                                <label className="block text-sm font-medium leading-6 text-gray-900 font-mono">Application Name</label>
                                <div className="mt-2">
                                    <input
                                        type="text"
                                        disabled
                                        defaultValue="VulnCheck"
                                        className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-vulncheck-blue sm:text-sm sm:leading-6 disabled:bg-gray-50 disabled:text-gray-500 font-mono"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium leading-6 text-gray-900 font-mono">Backend API URL</label>
                                <div className="mt-2">
                                    <input
                                        type="text"
                                        disabled
                                        defaultValue="http://localhost:8000/api/v1"
                                        className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-vulncheck-blue sm:text-sm sm:leading-6 disabled:bg-gray-50 disabled:text-gray-500 font-mono"
                                    />
                                </div>
                            </div>
                        </form>
                    </div>
                    )}

                    <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-6 mb-6">
                        <h3 className="text-lg font-bold text-gray-900 font-mono mb-4 border-b border-gray-100 pb-2">
                            User Management {userRole === 'admin' ? '(Admin)' : '(Read Only)'}
                        </h3>
                        {userRole === 'admin' && (
                            <>
                                {creationStatus.message && (
                                    <div className={`p-4 mb-4 text-sm rounded-md ${creationStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                        {creationStatus.message}
                                    </div>
                                )}
                                <form onSubmit={handleCreateUser} className="space-y-4 mb-8">
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-xs font-medium text-gray-700 font-mono mb-1">Username</label>
                                            <input
                                                type="text"
                                                required
                                                value={newUser.username}
                                                onChange={(e) => setNewUser({ ...newUser, username: e.target.value })}
                                                className="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-xs font-medium text-gray-700 font-mono mb-1">Email</label>
                                            <input
                                                type="email"
                                                required
                                                value={newUser.email}
                                                onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                                                className="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-xs font-medium text-gray-700 font-mono mb-1">Password</label>
                                            <input
                                                type="password"
                                                required
                                                value={newUser.password}
                                                onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                                                className="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-xs font-medium text-gray-700 font-mono mb-1">Role</label>
                                            <select
                                                value={newUser.role}
                                                onChange={(e) => setNewUser({ ...newUser, role: e.target.value })}
                                                className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                            >
                                                <option value="readonly">Readonly</option>
                                                <option value="editor">Editor</option>
                                                <option value="admin">Admin</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div className="flex justify-end">
                                        <button type="submit" className="bg-vulncheck-blue text-white px-4 py-2 rounded-sm text-sm font-semibold shadow-sm hover:bg-blue-600">
                                            Create User
                                        </button>
                                    </div>
                                </form>
                            </>
                        )}

                        <div className="border-t border-gray-100 pt-6">
                            <h4 className="text-sm font-bold text-gray-900 font-mono mb-4">Existing Users</h4>
                            {loadingUsers ? <p className="text-sm text-gray-500">Loading users...</p> : (
                                <div className="overflow-x-auto">
                                    <table className="min-w-full divide-y divide-gray-200">
                                        <thead>
                                            <tr>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Username</th>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Email</th>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Role</th>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Status</th>
                                                {userRole === 'admin' && <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Actions</th>}
                                            </tr>
                                        </thead>
                                        <tbody className="bg-white divide-y divide-gray-200 text-sm">
                                            {users.map((user) => (
                                                <tr key={user.id}>
                                                    <td className="px-3 py-2 whitespace-nowrap font-medium text-gray-900">{user.username}</td>
                                                    <td className="px-3 py-2 whitespace-nowrap text-gray-500">{user.email}</td>
                                                    <td className="px-3 py-2 whitespace-nowrap">
                                                        <span className="inline-flex items-center rounded-md bg-gray-50 px-2 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-500/10 hover:bg-gray-100 font-mono">
                                                            {user.role}
                                                        </span>
                                                    </td>
                                                    <td className="px-3 py-2 whitespace-nowrap">
                                                        {user.is_active ?
                                                            <span className="text-green-600 text-xs font-medium">Active</span> :
                                                            <span className="text-red-600 text-xs font-medium">Inactive</span>
                                                        }
                                                    </td>
                                                    {userRole === 'admin' && (
                                                        <td className="px-3 py-2 whitespace-nowrap text-right">
                                                            <button
                                                                onClick={() => setResetUser(user)}
                                                                className="text-vulncheck-blue hover:text-blue-900 text-xs font-medium font-mono border border-vulncheck-blue rounded px-2 py-1 hover:bg-blue-50"
                                                            >
                                                                Reset PW
                                                            </button>
                                                            <button
                                                                onClick={async () => {
                                                                    if (!confirm(`Force-reset MFA for ${user.username}? They will be able to log in with password only until they re-enrol.`)) return;
                                                                    try {
                                                                        const res = await api.post(`/auth/users/${user.id}/reset-mfa`);
                                                                        alert(res.data?.had_mfa ? `MFA reset for ${user.username}.` : `${user.username} had no MFA enabled.`);
                                                                    } catch (e: any) {
                                                                        alert(`Reset MFA failed: ${e?.response?.data?.detail || e?.message}`);
                                                                    }
                                                                }}
                                                                className="text-orange-600 hover:text-orange-900 text-xs font-medium font-mono border border-orange-300 rounded px-2 py-1 hover:bg-orange-50 ml-2"
                                                                title="Force-disable two-factor authentication for this user"
                                                            >
                                                                Reset MFA
                                                            </button>
                                                            <button
                                                                onClick={() => handleEditUser(user)}
                                                                className="text-vulncheck-blue hover:text-blue-900 text-xs font-medium font-mono border border-vulncheck-blue rounded px-2 py-1 hover:bg-blue-50 ml-2"
                                                            >
                                                                Edit
                                                            </button>
                                                            <button
                                                                onClick={() => setDeleteUser(user)}
                                                                className="text-red-600 hover:text-red-900 text-xs font-medium font-mono border border-red-300 rounded px-2 py-1 hover:bg-red-50 ml-2"
                                                            >
                                                                Delete
                                                            </button>
                                                        </td>
                                                    )}
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>
                    </div>

                    {userRole === 'admin' && (
                    <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-6 mb-6">
                        <h3 className="text-lg font-bold text-gray-900 font-mono mb-4 border-b border-gray-100 pb-2">
                            Integrations Status
                        </h3>
                        <ul role="list" className="divide-y divide-gray-100">
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">Wazuh SIEM</p>
                                        {wazuhConfigured ? (
                                            <p className="rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Active</p>
                                        ) : (
                                            <p className="rounded-md bg-yellow-50 px-2 py-1 text-xs font-medium text-yellow-800 ring-1 ring-inset ring-yellow-600/20">Config Required</p>
                                        )}
                                    </div>
                                    <div className="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
                                        <p className="truncate">Last sync: 2 mins ago</p>
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-4">
                                    <button onClick={() => setIsWazuhModalOpen(true)} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:block">Configure</button>
                                </div>
                            </li>
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">Tenable Nessus</p>
                                        {nessusConfigured ? (
                                            <p className="rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Active</p>
                                        ) : (
                                            <p className="rounded-md bg-yellow-50 px-2 py-1 text-xs font-medium text-yellow-800 ring-1 ring-inset ring-yellow-600/20">Config Required</p>
                                        )}
                                    </div>
                                    <div className="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
                                        <p className="truncate">{nessusConfig.base_url || 'No URL configured'}</p>
                                    </div>
                                    {nessusSyncStatus.message && (
                                        <p className={`mt-2 text-xs font-mono ${nessusSyncStatus.type === 'success' ? 'text-green-700' : nessusSyncStatus.type === 'error' ? 'text-red-700' : 'text-gray-500'}`}>
                                            {nessusSyncStatus.message}
                                        </p>
                                    )}
                                </div>
                                <div className="flex flex-none items-center gap-x-2">
                                    {nessusConfigured && (
                                        <button
                                            onClick={handleNessusSyncNow}
                                            disabled={nessusSyncing}
                                            className="rounded-md bg-vulncheck-blue px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 disabled:opacity-60"
                                            title="Trigger sync from Nessus now"
                                        >
                                            {nessusSyncing ? 'Syncing…' : 'Sync now'}
                                        </button>
                                    )}
                                    <button onClick={() => { setNessusTestStatus({ message: '', type: '' }); setIsNessusModalOpen(true); }} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Configure</button>
                                </div>
                            </li>
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">Universal AI Integration</p>
                                        {aiConfigured ? (
                                            <p className="rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Active</p>
                                        ) : (
                                            <p className="rounded-md bg-yellow-50 px-2 py-1 text-xs font-medium text-yellow-800 ring-1 ring-inset ring-yellow-600/20">Config Required</p>
                                        )}
                                    </div>
                                    <div className="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
                                        <p className="truncate">Model: {aiConfig.model || 'llama3'}</p>
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-4">
                                    <button onClick={() => setIsAIModalOpen(true)} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:block">Configure</button>
                                </div>
                            </li>
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">SMTP Email Service</p>
                                        {smtpConfigured ? (
                                            <p className="rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Active</p>
                                        ) : (
                                            <p className="rounded-md bg-yellow-50 px-2 py-1 text-xs font-medium text-yellow-800 ring-1 ring-inset ring-yellow-600/20">Config Required</p>
                                        )}
                                    </div>
                                    <div className="mt-1 flex items-center gap-x-2 text-xs leading-5 text-gray-500">
                                        <p className="truncate">{smtpConfig.host ? `Host: ${smtpConfig.host}` : 'No host configured'}</p>
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-4">
                                    <button onClick={() => setIsSmtpModalOpen(true)} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:block">Configure</button>
                                </div>
                            </li>
                        </ul>
                    </div>
                    )}

                    {userRole === 'admin' && (
                    <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-6 mb-6">
                        <h3 className="text-lg font-bold text-gray-900 font-mono mb-4 border-b border-gray-100 pb-2 flex items-center gap-x-3">
                            Security — MFA Enforcement
                            {mfaSavingStatus.message && (
                                <span className={`rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ${
                                    mfaSavingStatus.type === 'success'
                                        ? 'bg-green-50 text-green-700 ring-green-600/20'
                                        : mfaSavingStatus.type === 'error'
                                        ? 'bg-red-50 text-red-700 ring-red-600/20'
                                        : 'bg-gray-50 text-gray-600 ring-gray-300'
                                }`}>{mfaSavingStatus.message}</span>
                            )}
                        </h3>

                        <ul role="list" className="divide-y divide-gray-100">
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">Require TOTP for selected roles</p>
                                    <div className="mt-1 text-xs leading-5 text-gray-500">
                                        When on, any user in an enforced role without TOTP must enrol at next login before getting a session.
                                    </div>
                                </div>
                                <label className="flex flex-none items-center cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={mfaEnforced}
                                        onChange={(e) => handleSaveMfaEnforcement({ enforced: e.target.checked })}
                                        className="h-5 w-5 rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue"
                                    />
                                    <span className="ml-2 text-sm font-mono">{mfaEnforced ? 'Enforced' : 'Off'}</span>
                                </label>
                            </li>

                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">Enforced roles</p>
                                    <div className="mt-1 text-xs leading-5 text-gray-500">
                                        Pick which role tiers must enrol. Viewer accounts (read-only) usually opt-in only.
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-4 text-sm font-mono">
                                    {(['admin', 'editor', 'readonly'] as const).map((r) => (
                                        <label key={r} className="flex items-center gap-x-1 cursor-pointer">
                                            <input
                                                type="checkbox"
                                                disabled={!mfaEnforced}
                                                checked={mfaEnforcedRoles.includes(r)}
                                                onChange={(e) => {
                                                    const next = e.target.checked
                                                        ? Array.from(new Set([...mfaEnforcedRoles, r]))
                                                        : mfaEnforcedRoles.filter((x) => x !== r);
                                                    handleSaveMfaEnforcement({ roles: next });
                                                }}
                                                className="h-4 w-4 rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue disabled:opacity-50"
                                            />
                                            {r}
                                        </label>
                                    ))}
                                </div>
                            </li>

                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">Also enforce on SSO / LDAP users</p>
                                    <div className="mt-1 text-xs leading-5 text-gray-500">
                                        Default off — SSO/LDAP users rely on their IdP/AD MFA. Turn on to force an additional local TOTP layer.
                                    </div>
                                </div>
                                <label className="flex flex-none items-center cursor-pointer">
                                    <input
                                        type="checkbox"
                                        disabled={!mfaEnforced}
                                        checked={mfaEnforceSso}
                                        onChange={(e) => handleSaveMfaEnforcement({ enforceSso: e.target.checked })}
                                        className="h-5 w-5 rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue disabled:opacity-50"
                                    />
                                    <span className="ml-2 text-sm font-mono">{mfaEnforceSso ? 'On' : 'Off'}</span>
                                </label>
                            </li>
                        </ul>
                    </div>
                    )}

                    {userRole === 'admin' && (
                    <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-6 mb-6">
                        <h3 className="text-lg font-bold text-gray-900 font-mono mb-4 border-b border-gray-100 pb-2">
                            Notification Settings
                        </h3>

                        <ul role="list" className="divide-y divide-gray-100">
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">New Vulnerability Threshold</p>
                                        {notificationSavingStatus.message && (
                                            <p className={`rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ${
                                                notificationSavingStatus.type === 'success'
                                                    ? 'bg-green-50 text-green-700 ring-green-600/20'
                                                    : notificationSavingStatus.type === 'error'
                                                    ? 'bg-red-50 text-red-700 ring-red-600/20'
                                                    : 'bg-gray-50 text-gray-600 ring-gray-300'
                                            }`}>{notificationSavingStatus.message}</p>
                                        )}
                                    </div>
                                    <div className="mt-1 text-xs leading-5 text-gray-500">
                                        Minimum severity that triggers a &quot;new vulnerability&quot; email. Anything at or above this level will notify.
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-2">
                                    <select
                                        value={notificationMinSeverity}
                                        onChange={(e) => handleSaveNotificationMinSeverity(e.target.value as 'critical' | 'high' | 'medium' | 'low')}
                                        className="rounded-md border-0 py-1.5 pl-3 pr-8 text-sm text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-vulncheck-blue font-mono"
                                    >
                                        <option value="critical">Critical only</option>
                                        <option value="high">High and above</option>
                                        <option value="medium">Medium and above</option>
                                        <option value="low">Low and above (all)</option>
                                    </select>
                                </div>
                            </li>
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">New Vulnerability Delivery Mode</p>
                                    </div>
                                    <div className="mt-1 text-xs leading-5 text-gray-500">
                                        Digest = one summary email per recipient per sync run. Single = one email per CVE per recipient (legacy, can spam SMTP).
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-2">
                                    <select
                                        value={notificationMode}
                                        onChange={(e) => handleSaveNotificationMode(e.target.value as 'digest' | 'single')}
                                        className="rounded-md border-0 py-1.5 pl-3 pr-8 text-sm text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-vulncheck-blue font-mono"
                                    >
                                        <option value="digest">Digest (one mail per recipient)</option>
                                        <option value="single">Single (one mail per CVE)</option>
                                    </select>
                                </div>
                            </li>
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">SLA Breach Template</p>
                                        <p className="rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Active</p>
                                    </div>
                                    <div className="mt-1 text-xs leading-5 text-gray-500">
                                        Customize the HTML email sent when an SLA is breached.
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-2">
                                    <button onClick={() => renderPreview(emailTemplate)} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Preview</button>
                                    <button onClick={() => setIsTemplateModalOpen(true)} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Edit Template</button>
                                </div>
                            </li>
                            <li className="flex items-center justify-between gap-x-6 py-5">
                                <div className="min-w-0">
                                    <div className="flex items-start gap-x-3">
                                        <p className="text-sm font-semibold leading-6 text-gray-900 font-mono">New Vulnerability Template</p>
                                        <p className="rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Active</p>
                                    </div>
                                    <div className="mt-1 text-xs leading-5 text-gray-500">
                                        Customize the HTML email sent when a new vulnerability is detected.
                                    </div>
                                </div>
                                <div className="flex flex-none items-center gap-x-2">
                                    <button onClick={() => renderPreview(newVulnTemplate)} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Preview</button>
                                    <button onClick={() => setIsNewVulnTemplateModalOpen(true)} className="rounded-md bg-white px-2.5 py-1.5 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Edit Template</button>
                                </div>
                            </li>
                        </ul>
                    </div>
                    )}
                </div>

                {/* Profile/User Settings */}
                <div className="lg:col-span-1">
                    <MfaCard />
                    <div className="bg-white border border-gray-200 shadow-sm rounded-sm p-6 mt-4">
                        <h3 className="text-lg font-bold text-gray-900 font-mono mb-4 border-b border-gray-100 pb-2">
                            Your Profile
                        </h3>
                        <div className="text-center">
                            <div className="mx-auto h-20 w-20 rounded-full bg-gray-300 flex items-center justify-center text-xl font-bold text-gray-600 mb-4">
                                {currentUserInfo?.username?.slice(0, 2).toUpperCase() || '??'}
                            </div>
                            <h3 className="text-base font-semibold leading-7 tracking-tight text-gray-900">{currentUserInfo?.username || 'Unknown'}</h3>
                            <p className="text-sm font-semibold leading-6 text-vulncheck-blue font-mono capitalize">{currentUserInfo?.role || 'Unknown'}</p>
                            <ul role="list" className="mt-6 space-y-4 text-left border-t border-gray-100 pt-6">
                                <li className="flex items-center gap-x-3 text-sm text-gray-500">
                                    <span className="font-mono text-xs text-gray-400 w-16">EMAIL</span>
                                    <span>{currentUserInfo?.email || 'N/A'}</span>
                                </li>
                                <li className="flex items-center gap-x-3 text-sm text-gray-500">
                                    <span className="font-mono text-xs text-gray-400 w-16">ROLE</span>
                                    <span className="capitalize">{currentUserInfo?.role || 'N/A'}</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            {/* Wazuh Config Modal */}
            {isWazuhModalOpen && (
                <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">Wazuh SIEM Configuration</h3>

                        {configStatus.message && isWazuhModalOpen && (
                            <div className={`p-3 mb-4 text-sm rounded-md ${configStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                {configStatus.message}
                            </div>
                        )}

                        <p className="text-sm text-gray-500 mb-6">Configure the connection to your Wazuh Manager.</p>

                        <form className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 font-mono">Wazuh Manager API URL</label>
                                <input
                                    type="text"
                                    value={wazuhConfig.api_url}
                                    onChange={(e) => setWazuhConfig({ ...wazuhConfig, api_url: 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 h-12 px-4"
                                    placeholder="https://10.10.66.100:55000"
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 font-mono">Username</label>
                                    <input
                                        type="text"
                                        value={wazuhConfig.username}
                                        onChange={(e) => setWazuhConfig({ ...wazuhConfig, username: 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 h-12 px-4"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 font-mono">Password</label>
                                    <input
                                        type="password"
                                        value={wazuhConfig.password}
                                        onChange={(e) => setWazuhConfig({ ...wazuhConfig, password: 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 h-12 px-4"
                                    />
                                </div>
                            </div>

                            <div className="border-t border-gray-100 pt-4 mt-2">
                                <h4 className="text-sm font-bold text-gray-900 font-mono mb-4 flex items-center gap-2">
                                    <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                                    Indexer (OpenSearch) - Required for Vulns 4.8+
                                </h4>

                                <div className="space-y-4">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 font-mono">Indexer URL</label>
                                        <input
                                            type="text"
                                            value={wazuhConfig.indexer_url}
                                            onChange={(e) => setWazuhConfig({ ...wazuhConfig, indexer_url: 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 h-12 px-4"
                                            placeholder="https://10.10.66.102:9200"
                                        />
                                    </div>

                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 font-mono">Indexer Username</label>
                                            <input
                                                type="text"
                                                value={wazuhConfig.indexer_username}
                                                onChange={(e) => setWazuhConfig({ ...wazuhConfig, indexer_username: 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 h-12 px-4"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-700 font-mono">Indexer Password</label>
                                            <input
                                                type="password"
                                                value={wazuhConfig.indexer_password}
                                                onChange={(e) => setWazuhConfig({ ...wazuhConfig, indexer_password: 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 h-12 px-4"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <div className="flex justify-end gap-2 mt-6">
                            <button
                                type="button"
                                onClick={() => { setIsWazuhModalOpen(false); setConfigStatus({ message: '', type: '' }); }}
                                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                            >
                                Close
                            </button>
                            <button
                                type="button"
                                onClick={handleSaveWazuhConfig}
                                className="px-4 py-2 text-sm font-medium text-white bg-vulncheck-blue rounded-md hover:bg-blue-600"
                            >
                                Save Config
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Nessus Config Modal */}
            {isNessusModalOpen && (
                <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-lg w-full p-6">
                        <h3 className="text-lg font-bold mb-4 font-mono">Tenable Nessus Configuration</h3>

                        {configStatus.message && isNessusModalOpen && (
                            <div className={`p-3 mb-4 text-sm rounded-md ${configStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                {configStatus.message}
                            </div>
                        )}

                        <div className="space-y-3">
                            <div>
                                <label className="block text-sm font-medium text-gray-700">Base URL</label>
                                <input
                                    type="text"
                                    value={nessusConfig.base_url}
                                    onChange={(e) => setNessusConfig({ ...nessusConfig, base_url: e.target.value })}
                                    placeholder="https://nessus.local:8834"
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm px-3 py-1.5 ring-1 ring-inset ring-gray-300 font-mono text-sm"
                                />
                            </div>

                            <div className="grid grid-cols-1 gap-3">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Access Key</label>
                                    <input
                                        type="text"
                                        value={nessusConfig.access_key}
                                        onChange={(e) => setNessusConfig({ ...nessusConfig, access_key: e.target.value })}
                                        placeholder="64-character API access key"
                                        autoComplete="off"
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm px-3 py-1.5 ring-1 ring-inset ring-gray-300 font-mono text-xs"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Secret Key</label>
                                    <input
                                        type="password"
                                        value={nessusConfig.secret_key}
                                        onChange={(e) => setNessusConfig({ ...nessusConfig, secret_key: e.target.value })}
                                        placeholder="••••"
                                        autoComplete="new-password"
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm px-3 py-1.5 ring-1 ring-inset ring-gray-300 font-mono text-xs"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700">Default Scan IDs <span className="text-gray-400 text-xs">(comma-separated, optional)</span></label>
                                <input
                                    type="text"
                                    value={nessusConfig.default_scan_ids}
                                    onChange={(e) => setNessusConfig({ ...nessusConfig, default_scan_ids: e.target.value })}
                                    placeholder="12, 17, 24"
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm px-3 py-1.5 ring-1 ring-inset ring-gray-300 font-mono text-sm"
                                />
                                <p className="text-[11px] text-gray-500 mt-1">Used when scheduled syncs or the &quot;Sync now&quot; button fire without an explicit scan list.</p>
                            </div>

                            <div className="flex items-center gap-2 pt-2">
                                <input
                                    id="nessus-verify-ssl"
                                    type="checkbox"
                                    checked={nessusConfig.verify_ssl}
                                    onChange={(e) => setNessusConfig({ ...nessusConfig, verify_ssl: e.target.checked })}
                                    className="rounded border-gray-300"
                                />
                                <label htmlFor="nessus-verify-ssl" className="text-sm text-gray-700">Verify SSL certificate (recommended)</label>
                            </div>

                            <div className="flex items-center gap-2">
                                <input
                                    id="nessus-auto-create"
                                    type="checkbox"
                                    checked={nessusConfig.auto_create_assets}
                                    onChange={(e) => setNessusConfig({ ...nessusConfig, auto_create_assets: e.target.checked })}
                                    className="rounded border-gray-300"
                                />
                                <label htmlFor="nessus-auto-create" className="text-sm text-gray-700">Auto-create assets when no hostname/IP match exists</label>
                            </div>

                            {nessusTestStatus.message && (
                                <div className={`text-xs font-mono p-2 rounded ${nessusTestStatus.type === 'success' ? 'bg-green-50 text-green-700' : nessusTestStatus.type === 'error' ? 'bg-red-50 text-red-700' : 'bg-gray-50 text-gray-600'}`}>
                                    {nessusTestStatus.message}
                                </div>
                            )}
                        </div>

                        <div className="flex items-center justify-between mt-6 gap-2">
                            <button onClick={handleTestNessus} className="px-3 py-1.5 text-sm font-mono border border-vulncheck-blue text-vulncheck-blue rounded hover:bg-blue-50">Test connection</button>
                            <div className="flex gap-2">
                                <button onClick={() => setIsNessusModalOpen(false)} className="px-3 py-1.5 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200">Cancel</button>
                                <button onClick={async () => { await handleSaveNessusConfig(); }} className="px-3 py-1.5 text-sm bg-vulncheck-blue text-white rounded hover:bg-blue-600">Save</button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* AI Config Modal */}
            {isAIModalOpen && (
                <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 text-gray-900 border-b pb-2">AI Integration Settings</h3>

                        {configStatus.message && isAIModalOpen && (
                            <div className={`p-3 mb-4 text-sm rounded-md ${configStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                {configStatus.message}
                            </div>
                        )}

                        <form className="space-y-4">
                            <div>
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1 uppercase tracking-wider">AI Provider</label>
                                <select
                                    value={aiConfig.provider}
                                    onChange={(e) => {
                                        const newProvider = e.target.value;
                                        let defaultModel = 'llama3';
                                        let defaultUrl = '';

                                        switch (newProvider) {
                                            case 'openai': defaultModel = 'gpt-4o'; break;
                                            case 'anthropic': defaultModel = 'claude-3-5-sonnet-20240620'; break;
                                            case 'deepseek': defaultModel = 'deepseek-chat'; defaultUrl = 'https://api.deepseek.com'; break;
                                            case 'gemini': defaultModel = 'gemini-1.5-pro'; break;
                                            case 'ollama': defaultModel = 'llama3'; defaultUrl = 'http://localhost:11434/v1'; break;
                                            case 'infomaniak': defaultModel = 'llama3'; break;
                                        }

                                        setAiConfig({
                                            ...aiConfig,
                                            provider: newProvider,
                                            model: defaultModel,
                                            base_url: defaultUrl
                                        });
                                    }}
                                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm h-11"
                                >
                                    <option value="infomaniak">Infomaniak AI</option>
                                    <option value="openai">OpenAI (GPT-4o, etc.)</option>
                                    <option value="anthropic">Anthropic (Claude 3.5)</option>
                                    <option value="gemini">Google Gemini</option>
                                    <option value="deepseek">DeepSeek</option>
                                    <option value="ollama">Ollama (Localhost)</option>
                                </select>
                            </div>

                            {aiConfig.provider === 'infomaniak' && (
                                <div>
                                    <label className="block text-xs font-medium text-gray-700 font-mono mb-1 uppercase tracking-wider">Product ID</label>
                                    <input
                                        type="text"
                                        value={aiConfig.product_id}
                                        onChange={(e) => setAiConfig({ ...aiConfig, product_id: e.target.value })}
                                        placeholder="e.g. 12345"
                                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm h-11 px-3"
                                    />
                                </div>
                            )}

                            {(aiConfig.provider === 'ollama' || aiConfig.provider === 'openai' || aiConfig.provider === 'anthropic' || aiConfig.provider === 'deepseek') && (
                                <div>
                                    <label className="block text-xs font-medium text-gray-700 font-mono mb-1 uppercase tracking-wider">
                                        {aiConfig.provider === 'ollama' ? 'Ollama API URL' : 'Custom Base URL (Optional)'}
                                    </label>
                                    <input
                                        type="text"
                                        value={aiConfig.base_url}
                                        onChange={(e) => setAiConfig({ ...aiConfig, base_url: e.target.value })}
                                        placeholder={aiConfig.provider === 'ollama' ? 'http://localhost:11434/v1/chat/completions' : 'Leave empty for default'}
                                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm h-11 px-3"
                                    />
                                </div>
                            )}

                            {aiConfig.provider !== 'ollama' && (
                                <div>
                                    <label className="block text-xs font-medium text-gray-700 font-mono mb-1 uppercase tracking-wider">API Token / Key</label>
                                    <input
                                        type="password"
                                        value={aiConfig.api_token}
                                        onChange={(e) => setAiConfig({ ...aiConfig, api_token: e.target.value })}
                                        placeholder="sk-..."
                                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm h-11 px-3"
                                    />
                                </div>
                            )}

                            <div>
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1 uppercase tracking-wider">AI Model</label>
                                <select
                                    value={aiConfig.model}
                                    onChange={(e) => setAiConfig({ ...aiConfig, model: e.target.value })}
                                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm h-11"
                                >
                                    {aiConfig.provider === 'infomaniak' && (
                                        <>
                                            <option value="llama3">Llama 3.3</option>
                                            <option value="mistral3">Mistral 3</option>
                                            <option value="granite">Granite 3.1 8B</option>
                                            <option value="qwen3">Qwen 3</option>
                                            <option value="gemma3n">Gemma 3n</option>
                                            <option value="mixtral">Mixtral</option>
                                            <option value="mistral24b">Mistral 24B</option>
                                        </>
                                    )}
                                    {aiConfig.provider === 'openai' && (
                                        <>
                                            <option value="gpt-5.2">GPT-5.2 (Latest)</option>
                                            <option value="gpt-4.1">GPT-4.1 (1M Context)</option>
                                            <option value="gpt-4o">GPT-4o</option>
                                            <option value="o3">o3 (Reasoning)</option>
                                            <option value="o3-mini">o3-mini</option>
                                        </>
                                    )}
                                    {aiConfig.provider === 'anthropic' && (
                                        <>
                                            <option value="claude-opus-4.5">Claude Opus 4.5 (Latest)</option>
                                            <option value="claude-sonnet-4.5">Claude Sonnet 4.5</option>
                                            <option value="claude-haiku-4.5">Claude Haiku 4.5</option>
                                        </>
                                    )}
                                    {aiConfig.provider === 'deepseek' && (
                                        <>
                                            <option value="deepseek-chat">DeepSeek-V3</option>
                                            <option value="deepseek-reasoner">DeepSeek-R1 (Reasoner)</option>
                                        </>
                                    )}
                                    {aiConfig.provider === 'gemini' && (
                                        <>
                                            <option value="gemini-3-pro">Gemini 3 Pro (Latest)</option>
                                            <option value="gemini-3-flash">Gemini 3 Flash</option>
                                            <option value="gemini-2.5-pro">Gemini 2.5 Pro</option>
                                        </>
                                    )}
                                    {aiConfig.provider === 'ollama' && (
                                        <>
                                            <option value="llama3.3">Llama 3.3</option>
                                            <option value="mistral">Mistral</option>
                                            <option value="codellama">CodeLlama</option>
                                            <option value="phi4">Phi-4</option>
                                        </>
                                    )}
                                    <option value="custom">Custom Model...</option>
                                </select>
                            </div>

                            {aiConfig.model === 'custom' && (
                                <div>
                                    <label className="block text-xs font-medium text-gray-700 font-mono mb-1 uppercase tracking-wider">Custom Model Name</label>
                                    <input
                                        type="text"
                                        onChange={(e) => setAiConfig({ ...aiConfig, model: e.target.value })}
                                        placeholder="Enter model identifier..."
                                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm h-11 px-3"
                                    />
                                </div>
                            )}
                        </form>

                        <div className="flex justify-end gap-2 mt-8 pt-4 border-t">
                            <button
                                type="button"
                                onClick={() => { setIsAIModalOpen(false); setConfigStatus({ message: '', type: '' }); }}
                                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
                            >
                                Close
                            </button>
                            <button
                                type="button"
                                onClick={handleSaveAIConfig}
                                className="px-6 py-2 text-sm font-bold text-white bg-vulncheck-blue rounded-md hover:bg-blue-600 shadow-sm transition-colors"
                            >
                                Save Configuration
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Password Reset Modal */}
            {resetUser && (
                <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">Reset Password: <span className="text-vulncheck-blue">{resetUser.username}</span></h3>

                        {resetStatus.message && (
                            <div className={`p-3 mb-4 text-sm rounded-md ${resetStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                {resetStatus.message}
                            </div>
                        )}

                        <form onSubmit={handleResetPassword}>
                            <div className="mb-4">
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1">New Password</label>
                                <input
                                    type="password"
                                    required
                                    value={resetPassword}
                                    onChange={(e) => setResetPassword(e.target.value)}
                                    placeholder="Enter new password"
                                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                />
                            </div>

                            <div className="flex justify-end gap-2 mt-6">
                                <button
                                    type="button"
                                    onClick={() => {
                                        setResetUser(null);
                                        setResetPassword('');
                                        setResetStatus({ message: '', type: '' });
                                    }}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                                >
                                    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"
                                >
                                    Reset Password
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Delete User Confirmation Modal */}
            {deleteUser && (
                <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">Delete User: <span className="text-red-600">{deleteUser.username}</span></h3>

                        {deleteStatus.message && (
                            <div className="p-3 mb-4 text-sm rounded-md bg-red-50 text-red-700">
                                {deleteStatus.message}
                            </div>
                        )}

                        <p className="text-sm text-gray-600 mb-6">
                            Are you sure you want to delete this user? This action cannot be undone.
                        </p>

                        <div className="flex justify-end gap-2">
                            <button
                                type="button"
                                onClick={() => {
                                    setDeleteUser(null);
                                    setDeleteStatus({ message: '', type: '' });
                                }}
                                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                            >
                                Cancel
                            </button>
                            <button
                                type="button"
                                onClick={handleDeleteUser}
                                className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700"
                            >
                                Delete User
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* SMTP Config Modal */}
            {isSmtpModalOpen && (
                <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-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
                        <h3 className="text-lg font-bold mb-4 font-mono">SMTP Configuration</h3>

                        {configStatus.message && isSmtpModalOpen && (
                            <div className={`p-3 mb-4 text-sm rounded-md ${configStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                {configStatus.message}
                            </div>
                        )}

                        <p className="text-sm text-gray-500 mb-6">Configure the email server for notifications.</p>

                        <form className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-xs font-medium text-gray-700 font-mono mb-1">SMTP Host</label>
                                    <input
                                        type="text"
                                        value={smtpConfig.host}
                                        onChange={(e) => setSmtpConfig({ ...smtpConfig, host: e.target.value })}
                                        placeholder="smtp.example.com"
                                        className="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-xs font-medium text-gray-700 font-mono mb-1">Port</label>
                                    <input
                                        type="text"
                                        value={smtpConfig.port}
                                        onChange={(e) => setSmtpConfig({ ...smtpConfig, port: e.target.value })}
                                        placeholder="587"
                                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-xs font-medium text-gray-700 font-mono mb-1">Username</label>
                                    <input
                                        type="text"
                                        value={smtpConfig.username}
                                        onChange={(e) => setSmtpConfig({ ...smtpConfig, username: e.target.value })}
                                        className="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-xs font-medium text-gray-700 font-mono mb-1">Password</label>
                                    <input
                                        type="password"
                                        value={smtpConfig.password}
                                        onChange={(e) => setSmtpConfig({ ...smtpConfig, password: e.target.value })}
                                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1">From Address</label>
                                <input
                                    type="text"
                                    value={smtpConfig.from_address}
                                    onChange={(e) => setSmtpConfig({ ...smtpConfig, from_address: e.target.value })}
                                    placeholder="noreply@example.com"
                                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                />
                            </div>

                            <div className="flex items-center">
                                <input
                                    id="use_tls"
                                    type="checkbox"
                                    checked={smtpConfig.use_tls}
                                    onChange={(e) => setSmtpConfig({ ...smtpConfig, use_tls: e.target.checked })}
                                    className="h-4 w-4 rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue"
                                />
                                <label htmlFor="use_tls" className="ml-2 block text-sm text-gray-900">
                                    Use TLS
                                </label>
                            </div>

                            <div className="border-t border-gray-100 pt-4 mt-6">
                                <h4 className="text-sm font-bold text-gray-900 font-mono mb-4">Test Connection</h4>
                                <div className="flex gap-2">
                                    <input
                                        type="email"
                                        value={testEmail}
                                        onChange={(e) => setTestEmail(e.target.value)}
                                        placeholder="recipient@example.com"
                                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                    />
                                    <button
                                        type="button"
                                        onClick={handleTestConnection}
                                        className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 whitespace-nowrap"
                                    >
                                        Send Test Email
                                    </button>
                                </div>
                                {testEmailStatus.message && (
                                    <p className={`mt-2 text-xs ${testEmailStatus.type === 'success' ? 'text-green-600' : testEmailStatus.type === 'error' ? 'text-red-600' : 'text-gray-500'}`}>
                                        {testEmailStatus.message}
                                    </p>
                                )}
                            </div>

                            <div className="border-t border-gray-100 pt-4 mt-4">
                                <h4 className="text-sm font-bold text-gray-900 font-mono mb-2">Bulk Notifications</h4>
                                <p className="text-xs text-gray-500 mb-3">
                                    Send email notifications for all existing CRITICAL and HIGH vulnerabilities that haven&apos;t been notified yet.
                                </p>
                                <button
                                    type="button"
                                    onClick={async () => {
                                        setTestEmailStatus({ message: 'Sending notifications...', type: 'loading' });
                                        try {
                                            const res = await api.post('/api/v1/notifications/notify-critical');
                                            setTestEmailStatus({
                                                message: `${res.data.message} (Sent: ${res.data.sent}, Failed: ${res.data.failed})`,
                                                type: 'success'
                                            });
                                        } catch (err: any) {
                                            setTestEmailStatus({
                                                message: err.response?.data?.detail || 'Failed to send notifications',
                                                type: 'error'
                                            });
                                        }
                                    }}
                                    className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700"
                                >
                                    🚨 Notify All Critical/High
                                </button>
                            </div>
                        </form>

                        <div className="flex justify-end gap-2 mt-6">
                            <button
                                type="button"
                                onClick={() => { setIsSmtpModalOpen(false); setConfigStatus({ message: '', type: '' }); }}
                                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                            >
                                Close
                            </button>
                            <button
                                type="button"
                                onClick={handleSaveSmtpConfig}
                                className="px-4 py-2 text-sm font-medium text-white bg-vulncheck-blue rounded-md hover:bg-blue-600"
                            >
                                Save Config
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Email Template Modal */}
            {isTemplateModalOpen && (
                <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-4xl w-full p-6 h-[90vh] flex flex-col">
                        <div className="flex justify-between items-center mb-4">
                            <h3 className="text-lg font-bold font-mono">Edit SLA Breach Template</h3>
                            <button onClick={() => setIsTemplateModalOpen(false)} className="text-gray-400 hover:text-gray-500">
                                <span className="sr-only">Close</span>
                                <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        {configStatus.message && isTemplateModalOpen && (
                            <div className={`p-3 mb-4 text-sm rounded-md ${configStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                {configStatus.message}
                            </div>
                        )}

                        <form className="flex-1 flex flex-col space-y-4 overflow-hidden">
                            <div>
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1">Subject</label>
                                <input
                                    type="text"
                                    value={emailTemplate.subject}
                                    onChange={(e) => setEmailTemplate({ ...emailTemplate, subject: e.target.value })}
                                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm font-mono"
                                />
                            </div>

                            <div className="flex-1 flex flex-col">
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1">
                                    HTML Body
                                    <span className="ml-2 text-gray-500 font-normal">Available variables: {'{{cve_id}}'}, {'{{severity}}'}, {'{{asset_hostname}}'}, {'{{hours_overdue}}'}, {'{{assigned_user}}'}, {'{{dashboard_url}}'}</span>
                                </label>
                                <textarea
                                    value={emailTemplate.body}
                                    onChange={(e) => setEmailTemplate({ ...emailTemplate, body: e.target.value })}
                                    className="block w-full h-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm font-mono text-xs"
                                />
                            </div>
                        </form>

                        <div className="flex justify-between mt-6 pt-4 border-t border-gray-100">
                            <button
                                type="button"
                                onClick={() => renderPreview(emailTemplate)}
                                className="px-4 py-2 text-sm font-medium text-vulncheck-blue bg-blue-50 border border-vulncheck-blue rounded-md hover:bg-blue-100"
                            >
                                Preview
                            </button>
                            <div className="flex gap-2">
                                <button
                                    type="button"
                                    onClick={() => { setIsTemplateModalOpen(false); setConfigStatus({ message: '', type: '' }); }}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                                >
                                    Close
                                </button>
                                <button
                                    type="button"
                                    onClick={handleSaveEmailTemplate}
                                    className="px-4 py-2 text-sm font-medium text-white bg-vulncheck-blue rounded-md hover:bg-blue-600"
                                >
                                    Save Template
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* New Vulnerability Template Modal */}
            {isNewVulnTemplateModalOpen && (
                <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-4xl w-full p-6 h-[90vh] flex flex-col">
                        <div className="flex justify-between items-center mb-4">
                            <h3 className="text-lg font-bold font-mono">Edit New Vulnerability Template</h3>
                            <button onClick={() => setIsNewVulnTemplateModalOpen(false)} className="text-gray-400 hover:text-gray-500">
                                <span className="sr-only">Close</span>
                                <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        {configStatus.message && isNewVulnTemplateModalOpen && (
                            <div className={`p-3 mb-4 text-sm rounded-md ${configStatus.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                {configStatus.message}
                            </div>
                        )}

                        <form className="flex-1 flex flex-col space-y-4 overflow-hidden">
                            <div>
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1">Subject</label>
                                <input
                                    type="text"
                                    value={newVulnTemplate.subject}
                                    onChange={(e) => setNewVulnTemplate({ ...newVulnTemplate, subject: e.target.value })}
                                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm font-mono"
                                />
                            </div>

                            <div className="flex-1 flex flex-col">
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1">
                                    HTML Body
                                    <span className="ml-2 text-gray-500 font-normal">Available variables: {'{{cve_id}}'}, {'{{severity}}'}, {'{{severity_upper}}'}, {'{{cvss_score}}'}, {'{{asset_hostname}}'}, {'{{asset_ip}}'}, {'{{package_name}}'}, {'{{description}}'}, {'{{detected_at}}'}, {'{{dashboard_url}}'}</span>
                                </label>
                                <textarea
                                    value={newVulnTemplate.body}
                                    onChange={(e) => setNewVulnTemplate({ ...newVulnTemplate, body: e.target.value })}
                                    className="block w-full h-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm font-mono text-xs"
                                />
                            </div>
                        </form>

                        <div className="flex justify-between mt-6 pt-4 border-t border-gray-100">
                            <button
                                type="button"
                                onClick={() => renderPreview(newVulnTemplate)}
                                className="px-4 py-2 text-sm font-medium text-vulncheck-blue bg-blue-50 border border-vulncheck-blue rounded-md hover:bg-blue-100"
                            >
                                Preview
                            </button>
                            <div className="flex gap-2">
                                <button
                                    type="button"
                                    onClick={() => { setIsNewVulnTemplateModalOpen(false); setConfigStatus({ message: '', type: '' }); }}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                                >
                                    Close
                                </button>
                                <button
                                    type="button"
                                    onClick={handleSaveNewVulnTemplate}
                                    className="px-4 py-2 text-sm font-medium text-white bg-vulncheck-blue rounded-md hover:bg-blue-600"
                                >
                                    Save Template
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Email Preview Modal */}
            {isPreviewOpen && (
                <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-gray-500 bg-opacity-75">
                    <div className="bg-white rounded-lg shadow-xl max-w-3xl w-full h-[85vh] flex flex-col">
                        <div className="flex justify-between items-center p-6 pb-4 border-b border-gray-100">
                            <h3 className="text-lg font-bold font-mono">Email Preview</h3>
                            <button onClick={() => setIsPreviewOpen(false)} className="text-gray-400 hover:text-gray-500">
                                <span className="sr-only">Close</span>
                                <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div className="px-6 py-2 bg-gray-50 border-b border-gray-100">
                            <p className="text-xs text-gray-500 font-mono">
                                This preview uses sample data. Variables like {'{{cve_id}}'} are replaced with example values.
                            </p>
                        </div>
                        <div className="flex-1 p-4 overflow-hidden">
                            <iframe
                                srcDoc={previewHtml}
                                className="w-full h-full border border-gray-200 rounded-md bg-white"
                                sandbox="allow-same-origin"
                                title="Email Preview"
                            />
                        </div>
                        <div className="flex justify-end p-6 pt-4 border-t border-gray-100">
                            <button
                                type="button"
                                onClick={() => setIsPreviewOpen(false)}
                                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                            >
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Edit User Modal */}
            {isEditUserModalOpen && editUser && (
                <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">Edit User: <span className="text-vulncheck-blue">{editUser.username}</span></h3>

                        <form onSubmit={handleUpdateUser} className="space-y-4">
                            <div>
                                <label className="block text-xs font-medium text-gray-700 font-mono mb-1">Email</label>
                                <input
                                    type="email"
                                    required
                                    value={editFormData.email}
                                    onChange={(e) => setEditFormData({ ...editFormData, email: e.target.value })}
                                    className="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-xs font-medium text-gray-700 font-mono mb-1">Role</label>
                                <select
                                    value={editFormData.role}
                                    onChange={(e) => setEditFormData({ ...editFormData, role: e.target.value })}
                                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                >
                                    <option value="readonly">Readonly</option>
                                    <option value="editor">Editor</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>

                            <div className="flex justify-end gap-2 mt-6">
                                <button
                                    type="button"
                                    onClick={() => {
                                        setIsEditUserModalOpen(false);
                                        setEditUser(null);
                                    }}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                                >
                                    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"
                                >
                                    Update User
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
