import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { AlertTriangle, CheckCircle, Clock, Filter, Search, MessageSquare, Shield, Bug, Settings } from 'lucide-react';
const VulnerabilityManager = ({ projectId }) => {
    const [vulnerabilities, setVulnerabilities] = useState([]);
    const [filteredVulnerabilities, setFilteredVulnerabilities] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [severityFilter, setSeverityFilter] = useState('all');
    const [statusFilter, setStatusFilter] = useState('all');
    const [typeFilter, setTypeFilter] = useState('all');
    const [selectedVulnerability, setSelectedVulnerability] = useState(null);
    const [updateDialogOpen, setUpdateDialogOpen] = useState(false);
    const [updateForm, setUpdateForm] = useState({
        status: 'open',
        notes: ''
    });
    const [updating, setUpdating] = useState(false);
    useEffect(() => {
        fetchVulnerabilities();
    }, [projectId]);
    useEffect(() => {
        filterVulnerabilities();
    }, [vulnerabilities, searchTerm, severityFilter, statusFilter, typeFilter]);
    const fetchVulnerabilities = async () => {
        setLoading(true);
        try {
            const response = await fetch(`/api/v1/projects/${projectId}/vulnerabilities`);
            const data = await response.json();
            setVulnerabilities(data.vulnerabilities || []);
        }
        catch (error) {
            console.error('Failed to fetch vulnerabilities:', error);
        }
        finally {
            setLoading(false);
        }
    };
    const filterVulnerabilities = () => {
        let filtered = vulnerabilities;
        // Search filter
        if (searchTerm) {
            filtered = filtered.filter(vuln => vuln.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                vuln.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
                vuln.service_name?.toLowerCase().includes(searchTerm.toLowerCase()));
        }
        // Severity filter
        if (severityFilter !== 'all') {
            filtered = filtered.filter(vuln => vuln.severity === severityFilter);
        }
        // Status filter
        if (statusFilter !== 'all') {
            filtered = filtered.filter(vuln => vuln.status === statusFilter);
        }
        // Type filter
        if (typeFilter !== 'all') {
            filtered = filtered.filter(vuln => vuln.type === typeFilter);
        }
        setFilteredVulnerabilities(filtered);
    };
    const updateVulnerability = async (vulnId) => {
        setUpdating(true);
        try {
            const response = await fetch(`/api/v1/vulnerabilities/${vulnId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(updateForm)
            });
            if (response.ok) {
                fetchVulnerabilities();
                setUpdateDialogOpen(false);
                setSelectedVulnerability(null);
                setUpdateForm({ status: 'open', notes: '' });
            }
        }
        catch (error) {
            console.error('Failed to update vulnerability:', error);
        }
        finally {
            setUpdating(false);
        }
    };
    const getSeverityColor = (severity) => {
        switch (severity) {
            case 'critical': return 'bg-red-500 hover:bg-red-600';
            case 'high': return 'bg-orange-500 hover:bg-orange-600';
            case 'medium': return 'bg-yellow-500 hover:bg-yellow-600';
            case 'low': return 'bg-blue-500 hover:bg-blue-600';
            default: return 'bg-gray-500 hover:bg-gray-600';
        }
    };
    const getStatusColor = (status) => {
        switch (status) {
            case 'open': return 'bg-red-100 text-red-800';
            case 'resolved': return 'bg-green-100 text-green-800';
            case 'ignored': return 'bg-gray-100 text-gray-800';
            default: return 'bg-gray-100 text-gray-800';
        }
    };
    const getTypeIcon = (type) => {
        switch (type) {
            case 'dependency': return _jsx(Bug, { className: "h-4 w-4" });
            case 'configuration': return _jsx(Settings, { className: "h-4 w-4" });
            case 'code': return _jsx(Shield, { className: "h-4 w-4" });
            default: return _jsx(AlertTriangle, { className: "h-4 w-4" });
        }
    };
    const openUpdateDialog = (vuln) => {
        setSelectedVulnerability(vuln);
        setUpdateForm({
            status: vuln.status,
            notes: ''
        });
        setUpdateDialogOpen(true);
    };
    const severityCounts = vulnerabilities.reduce((acc, vuln) => {
        acc[vuln.severity] = (acc[vuln.severity] || 0) + 1;
        return acc;
    }, {});
    const statusCounts = vulnerabilities.reduce((acc, vuln) => {
        acc[vuln.status] = (acc[vuln.status] || 0) + 1;
        return acc;
    }, {});
    if (loading) {
        return (_jsx("div", { className: "flex items-center justify-center h-64", children: _jsx("div", { className: "animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" }) }));
    }
    return (_jsxs("div", { className: "space-y-6", children: [_jsxs("div", { className: "grid grid-cols-1 md:grid-cols-4 gap-4", children: [_jsxs(Card, { children: [_jsxs(CardHeader, { className: "flex flex-row items-center justify-between space-y-0 pb-2", children: [_jsx(CardTitle, { className: "text-sm font-medium", children: "Total" }), _jsx(AlertTriangle, { className: "h-4 w-4 text-muted-foreground" })] }), _jsx(CardContent, { children: _jsx("div", { className: "text-2xl font-bold", children: vulnerabilities.length }) })] }), _jsxs(Card, { children: [_jsxs(CardHeader, { className: "flex flex-row items-center justify-between space-y-0 pb-2", children: [_jsx(CardTitle, { className: "text-sm font-medium", children: "Critical" }), _jsx("div", { className: "h-3 w-3 bg-red-500 rounded-full" })] }), _jsx(CardContent, { children: _jsx("div", { className: "text-2xl font-bold text-red-600", children: severityCounts.critical || 0 }) })] }), _jsxs(Card, { children: [_jsxs(CardHeader, { className: "flex flex-row items-center justify-between space-y-0 pb-2", children: [_jsx(CardTitle, { className: "text-sm font-medium", children: "High" }), _jsx("div", { className: "h-3 w-3 bg-orange-500 rounded-full" })] }), _jsx(CardContent, { children: _jsx("div", { className: "text-2xl font-bold text-orange-600", children: severityCounts.high || 0 }) })] }), _jsxs(Card, { children: [_jsxs(CardHeader, { className: "flex flex-row items-center justify-between space-y-0 pb-2", children: [_jsx(CardTitle, { className: "text-sm font-medium", children: "Open" }), _jsx(Clock, { className: "h-4 w-4 text-muted-foreground" })] }), _jsx(CardContent, { children: _jsx("div", { className: "text-2xl font-bold", children: statusCounts.open || 0 }) })] })] }), _jsxs(Card, { children: [_jsx(CardHeader, { children: _jsxs(CardTitle, { className: "flex items-center gap-2", children: [_jsx(Filter, { className: "h-5 w-5" }), "Filters"] }) }), _jsx(CardContent, { children: _jsxs("div", { className: "flex flex-wrap gap-4", children: [_jsx("div", { className: "flex-1 min-w-[200px]", children: _jsxs("div", { className: "relative", children: [_jsx(Search, { className: "absolute left-3 top-3 h-4 w-4 text-muted-foreground" }), _jsx(Input, { placeholder: "Search vulnerabilities...", value: searchTerm, onChange: (e) => setSearchTerm(e.target.value), className: "pl-10" })] }) }), _jsxs(Select, { value: severityFilter, onValueChange: setSeverityFilter, children: [_jsx(SelectTrigger, { className: "w-[150px]", children: _jsx(SelectValue, { placeholder: "Severity" }) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "all", children: "All Severities" }), _jsx(SelectItem, { value: "critical", children: "Critical" }), _jsx(SelectItem, { value: "high", children: "High" }), _jsx(SelectItem, { value: "medium", children: "Medium" }), _jsx(SelectItem, { value: "low", children: "Low" })] })] }), _jsxs(Select, { value: statusFilter, onValueChange: setStatusFilter, children: [_jsx(SelectTrigger, { className: "w-[150px]", children: _jsx(SelectValue, { placeholder: "Status" }) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "all", children: "All Status" }), _jsx(SelectItem, { value: "open", children: "Open" }), _jsx(SelectItem, { value: "resolved", children: "Resolved" }), _jsx(SelectItem, { value: "ignored", children: "Ignored" })] })] }), _jsxs(Select, { value: typeFilter, onValueChange: setTypeFilter, children: [_jsx(SelectTrigger, { className: "w-[150px]", children: _jsx(SelectValue, { placeholder: "Type" }) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "all", children: "All Types" }), _jsx(SelectItem, { value: "dependency", children: "Dependency" }), _jsx(SelectItem, { value: "configuration", children: "Configuration" }), _jsx(SelectItem, { value: "code", children: "Code" })] })] })] }) })] }), _jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsxs(CardTitle, { children: ["Vulnerabilities (", filteredVulnerabilities.length, ")"] }), _jsx(CardDescription, { children: "Security vulnerabilities found in your project and services." })] }), _jsx(CardContent, { children: filteredVulnerabilities.length === 0 ? (_jsxs("div", { className: "text-center py-8", children: [_jsx(CheckCircle, { className: "h-12 w-12 text-green-500 mx-auto mb-4" }), _jsx("h3", { className: "text-lg font-semibold", children: "No vulnerabilities found" }), _jsx("p", { className: "text-muted-foreground", children: vulnerabilities.length === 0
                                        ? "Your project looks secure!"
                                        : "No vulnerabilities match your current filters." })] })) : (_jsx("div", { className: "space-y-3", children: filteredVulnerabilities.map((vuln) => (_jsxs("div", { className: "flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50 transition-colors", children: [_jsxs("div", { className: "flex-1", children: [_jsxs("div", { className: "flex items-center gap-3 mb-2", children: [getTypeIcon(vuln.type), _jsx(Badge, { className: getSeverityColor(vuln.severity), children: vuln.severity.toUpperCase() }), _jsx("h4", { className: "font-medium", children: vuln.title }), _jsx(Badge, { variant: "outline", className: getStatusColor(vuln.status), children: vuln.status })] }), _jsx("p", { className: "text-sm text-muted-foreground mb-2", children: vuln.description }), _jsxs("div", { className: "flex items-center gap-4 text-xs text-muted-foreground", children: [_jsxs("span", { children: ["Found ", new Date(vuln.found_at).toLocaleDateString()] }), vuln.service_name && (_jsxs("span", { children: ["Service: ", vuln.service_name] })), vuln.resolved_at && (_jsxs("span", { children: ["Resolved ", new Date(vuln.resolved_at).toLocaleDateString()] }))] })] }), _jsx("div", { className: "flex items-center gap-2", children: _jsxs(Button, { variant: "outline", size: "sm", onClick: () => openUpdateDialog(vuln), children: [_jsx(MessageSquare, { className: "h-4 w-4 mr-2" }), "Update"] }) })] }, vuln.id))) })) })] }), _jsx(Dialog, { open: updateDialogOpen, onOpenChange: setUpdateDialogOpen, children: _jsxs(DialogContent, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Update Vulnerability" }), _jsx(DialogDescription, { children: "Update the status and add notes for this vulnerability." })] }), selectedVulnerability && (_jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "p-3 bg-muted rounded-lg", children: [_jsx("h4", { className: "font-medium", children: selectedVulnerability.title }), _jsx("p", { className: "text-sm text-muted-foreground", children: selectedVulnerability.description })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("label", { className: "text-sm font-medium", children: "Status" }), _jsxs(Select, { value: updateForm.status, onValueChange: (value) => setUpdateForm(prev => ({ ...prev, status: value })), children: [_jsx(SelectTrigger, { children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "open", children: "Open" }), _jsx(SelectItem, { value: "resolved", children: "Resolved" }), _jsx(SelectItem, { value: "ignored", children: "Ignored" })] })] })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("label", { className: "text-sm font-medium", children: "Notes" }), _jsx(Textarea, { placeholder: "Add notes about this vulnerability...", value: updateForm.notes, onChange: (e) => setUpdateForm(prev => ({ ...prev, notes: e.target.value })), rows: 3 })] }), _jsxs("div", { className: "flex justify-end gap-2", children: [_jsx(Button, { variant: "outline", onClick: () => setUpdateDialogOpen(false), children: "Cancel" }), _jsx(Button, { onClick: () => updateVulnerability(selectedVulnerability.id), disabled: updating, children: updating ? 'Updating...' : 'Update' })] })] }))] }) })] }));
};
