import React, { useEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { FaCog } from 'react-icons/fa';
import './Dashboard.css';

function Dashboard() {
    const navigate = useNavigate();
    const filterButtonRef = useRef(null);
    const [filterText, setFilterText] = useState(""); // Input value
    const [filteredPackets, setFilteredPackets] = useState([]); // Filtered packets
    const [allPackets, setAllPackets] = useState([]); // All packets
    const [filterActive, setFilterActive] = useState(false); // Filter active status



    const [isCapturing, setIsCapturing] = useState(false);
    const [isPaused, setIsPaused] = useState(false);
    const [capturedPackets, setCapturedPackets] = useState([]);
    const [trafficSummary, setTrafficSummary] = useState({ tcp: 0, udp: 0, icmp: 0, other: 0, total: 0 });
    const [selectedPacket, setSelectedPacket] = useState(null);
    const [interfaces, setInterfaces] = useState([]); // State for storing available interfaces
    const [selectedInterface, setSelectedInterface] = useState(''); // State for selected interface
    const usercredentials = JSON.parse(localStorage.getItem('user'));

    useEffect(() => {
        setAllPackets(capturedPackets);
    }, [capturedPackets]);

    // Logout function
    const handleLogout = (event) => {
        event.preventDefault();
        const confirmLogout = window.confirm("Are you sure you want to log out?");
        if (confirmLogout) {
            if (!localStorage.getItem('rememberMe')) {
                localStorage.removeItem('user');
            }
            navigate('/');
        }
        else console.log("User chose to stay logged in.");
    };

    const applyFilter = () => {
        if (filterText.trim() === "") {
            // If the filter text is empty, show all packets
            setFilteredPackets(allPackets);
            setFilterActive(false);
        } else {
            // Apply filter based on filterText
            // Filter packets based on the filter text
            const filteredPackets = allPackets.filter(packet =>
            packet.data.toLowerCase().includes(filterText.toLowerCase()) || // Filter by packet data
            packet.timestamp.toLowerCase().includes(filterText.toLowerCase()) // Filter by timestamp
    );
            setFilteredPackets(filteredPackets);
            setFilterActive(true);
        }
    };

    // Start packet capture
    const handleStartCapture = () => {
        if (!selectedInterface) {
            alert("Please select an interface first.");
            return;
        }

        fetch('http://127.0.0.1:5000/start', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ interface: selectedInterface }) // Pass the selected interface to the backend
        })
        .then(response => response.json())
        .then(data => {
            console.log(data.message);
            setIsCapturing(true);
            setIsPaused(false);
        })
        .catch(error => console.error('Error:', error));
    };

    // Stop packet capture
    const handleStopCapture = () => {
        fetch('http://127.0.0.1:5000/stop', { method: 'POST' })
            .then(response => response.json())
            .then(data => {
                console.log(data.message);

                if (Array.isArray(data.packets)) {
                    const newPackets = data.packets;
                    setCapturedPackets(prevPackets => {
                        const updatedPackets = [...prevPackets, ...newPackets];
                        updateTrafficSummary(updatedPackets);
                        return updatedPackets;
                    });
                } else {
                    console.error("Packets data is not an array:", data.packets);
                }

                setIsCapturing(false);
                setIsPaused(true);
            })
            .catch(error => console.error('Error:', error));
    };

    // Resume packet capture
    const handleResumeCapture = () => {
        fetch('http://127.0.0.1:5000/resume', { method: 'POST' })
            .then(response => response.json())
            .then(data => {
                console.log(data.message);
                setIsCapturing(true);
                setIsPaused(false);
            })
            .catch(error => console.error('Error:', error));
    };

    // Save capture to backend
    const handleSaveCapture = () => {
        fetch('http://127.0.0.1:5000/save', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                username: usercredentials.username,  // Send the username with the request
                packets: capturedPackets // Optionally send the captured packets, or modify the backend to handle it
            })
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
        })
        .catch(error => console.error('Error:', error));
    };

    // Update traffic summary based on captured packets
    const updateTrafficSummary = (packets) => {
        const summary = { tcp: 0, udp: 0, icmp: 0, other: 0, total: 0 };

        packets.forEach(packet => {
            if (packet.data) {
                if (packet.data.includes('TCP')) {
                    summary.tcp += 1;
                } else if (packet.data.includes('UDP')) {
                    summary.udp += 1;
                } else if (packet.data.includes('ICMP')) {
                    summary.icmp += 1;
                } else {
                    summary.other += 1;
                }
                summary.total += 1;
            }
        });

        setTrafficSummary(summary);
    };

    // Fetch captured packets periodically to display in real-time
    useEffect(() => {
        const interval = setInterval(() => {
            if (isCapturing) {
                fetch('http://127.0.0.1:5000/packets')
                    .then(response => response.json())
                    .then(data => {
                        if (Array.isArray(data.packets)) {
                            setCapturedPackets(data.packets);
                            updateTrafficSummary(data.packets);
                        } else {
                            console.error("Packets data is not an array:", data.packets);
                        }
                    })
                    .catch(error => console.error('Error fetching packets:', error));
            }
        }, 2000);

        return () => clearInterval(interval);
    }, [isCapturing]);

    // Function to handle packet selection for details view
    const handlePacketSelect = (packet, index) => {
        const packetDetails = {
            number: index + 1,
            time: packet.timestamp,
            source: packet.source_ip,
            destination: packet.destination_ip,
            protocol: packet.protocol,
            length: packet.length,
        };
        setSelectedPacket(packetDetails);
    };

    // Fetch interfaces when the component mounts
    useEffect(() => {
        fetch('http://127.0.0.1:5000/interfaces')
            .then(response => response.json())
            .then(data => {
                const interfacesList = data.interfaces || [];
                setInterfaces(interfacesList);
                if (interfacesList.length > 0) {
                    setSelectedInterface(interfacesList[0]); // Set default selected interface to the first one
                }
            })
            .catch(error => console.error('Error fetching interfaces:', error));
    }, []);

    return (
        <div className="dashboard-container">
            <div className="header">
                <div className="settings">
                    <Link to="/settings">
                        <FaCog className="settings-icon" style={{ fontSize: '30px' }} />
                    </Link>
                </div>

                <div className="saved-sessions">
                    <Link to="/saved-sessions">Saved Sessions</Link>
                </div>

                <div className="filter-bar">
                    <input
                        type="text"
                        placeholder="Try filtering your packets here!"
                        className="filter-input"
                        value={filterText} // Controlled input
                        onChange={(e) => setFilterText(e.target.value)} // Update filter text
                        onKeyDown={(e) => {
                            if (e.key === "Enter") applyFilter(); // Apply filter on Enter key press
                        }}
                    />
                    <div className="filter-button">
                        <button
                            ref={filterButtonRef}
                            onClick={applyFilter} // Call the filter function when clicked
                        >
                            Apply Filter
                        </button>
                    </div>
                </div>
                
                {/* Display the placeholder username */}
                <span className="user-name-dashboard">Hello, {usercredentials.username} </span>
                
                <div className="logout-container">
                    <Link to="/" onClick={handleLogout}>Log Out</Link>
                </div>
            </div>

            <div className="right-left-container">
                <div className="left-column">
                    <div className="packet-display-container">
                        <h2>Your Packets in Real-Time</h2>
                        <div className="packet-display-content">
                            {(filteredPackets.length > 0 || !filterActive) ? (
                                <ul>
                                    {(filterActive ? filteredPackets : allPackets).map((packet, index) => (
                                        <li
                                            key={index}
                                            onClick={() => handlePacketSelect(packet, index)}
                                            className={`packet-item ${selectedPacket?.number === index + 1 ? 'selected' : ''}`}
                                        >
                                            <strong>{packet.timestamp}</strong> - {packet.data}
                                        </li>
                                    ))}
                                </ul>
                            ) : (
                                <p>No packets found matching your filter.</p>
                            )}
                        </div>
                    </div>

                    <div className="packet-details-container">
                        <h2>Packet Details</h2>
                        {selectedPacket ? (
                            <div className="packet-details-content">
                                <p><strong>Number:</strong> {selectedPacket.number}</p>
                                <p><strong>Time:</strong> {selectedPacket.time}</p>
                                <p><strong>Source:</strong> {selectedPacket.source}</p>
                                <p><strong>Destination:</strong> {selectedPacket.destination}</p>
                                <p><strong>Protocol:</strong> {selectedPacket.protocol}</p>
                                <p><strong>Length:</strong> {selectedPacket.length} bits</p>
                            </div>
                        ) : (
                            <p>Select a packet to view details.</p>
                        )}
                    </div>
                </div>

                <div className="right-column">
                    <div className="capture-buttons-container">
                        <button onClick={handleStartCapture} disabled={isCapturing}>Start Capture</button>
                        <button onClick={handleStopCapture} disabled={!isCapturing}>Stop Capture</button>
                        <button onClick={handleResumeCapture} disabled={isCapturing || !isPaused}>Resume Capture</button>
                        <button onClick={handleSaveCapture} disabled={isCapturing || (!isCapturing && !isPaused)} className="save-button"> Save Capture </button>
                    </div>

                    <div className="interface-list-container">
                        <div className="interface-selection">
                            <h2><label htmlFor="interface-select">Select Your Interface:</label></h2>
                            <select
                                id="interface-select"
                                className="interface-dropdown"
                                value={selectedInterface}
                                onChange={(e) => setSelectedInterface(e.target.value)}
                            >
                                {interfaces.length > 0 ? (
                                    interfaces.map((iface, index) => (
                                        <option key={index} value={iface}>
                                            Interface {index + 1} - {iface}
                                        </option>
                                    ))
                                ) : (
                                    <option value="" disabled>No interfaces available</option>
                                )}
                            </select>
                            <h3>Current Interface: {selectedInterface || 'None selected'}</h3>
                        </div>
                    </div>

                    <div className="traffic-summary-container">
                        <h2>Your Network Traffic Summary</h2>
                        <div className="traffic-summary-content">
                            <p>Total Packets: {trafficSummary.total}</p>
                            <p>TCP: {trafficSummary.tcp}</p>
                            <p>UDP: {trafficSummary.udp}</p>
                            <p>ICMP: {trafficSummary.icmp}</p>
                            <p>Other Protocols: {trafficSummary.other}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Dashboard;
