import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import './SavedSessions.css';


function SavedSessions() {
    const [selectedSession, setSelectedSession] = useState(null);
    const [sessions, setSessions] = useState([]);
    const [capturedPackets, setCapturedPackets] = useState([]);
    const [error, setError] = useState('');
    const [selectedPacket, setSelectedPacket] = useState(null);
    const usercredentials = JSON.parse(localStorage.getItem('user'));

    // Fetch saved sessions from the Flask API
    useEffect(() => {
        const fetchSessions = async () => {
            try {
                const session = await fetch('http://127.0.0.1:5000/saved-sessions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(usercredentials)
            });

            const sessionresponse = await session.json();
            if (sessionresponse.success) {
                console.log("this is saved sessions:", sessionresponse.saved_sessions);
                setSessions(sessionresponse.saved_sessions);
            } else {
                setError(sessionresponse.message);
                console.log("this is saved sessions response:", sessionresponse.success);
            }
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again later.');
        }
    };


        fetchSessions();
    }, []);

    // Fetch captured packets based on selected session
    const fetchPackets = async (session) => {
        try {
            const response = await fetch('http://127.0.0.1:5000/saved-packets', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ session_id: session.session_id }),
            });
            const result = await response.json();
            if (result.success) {
                setCapturedPackets(result.capturedpackets);
            } else {
                setError(result.message);
            }
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again later.');
        }
    };

    // Handle selecting a session and fetching its packets
    const handleViewDetails = (session) => {
        setSelectedSession(session);
        fetchPackets(session);
    };

    // 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.packetlength,
        };
        setSelectedPacket(packetDetails);
    };

    function downloadSession(usercredentials, session) {
        // Prepare the data for the request
        const data = {
            username: usercredentials.username,
            session_number: session.session_number,
            captured_packets: capturedPackets,
        };
        console.log(capturedPackets)
    
        // Send POST request to the Flask API to generate the .pcap file
        fetch('http://127.0.0.1:5000/download_session', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())  // Use .blob() to handle the .pcap file
        .then(result => {
             // Check if the server responded with a success status
        if (result.success) {
            // Now use the file path to fetch the actual .pcap file as a Blob
            fetch(result.pcap_file_path)
                .then(response => response.blob())  // Fetch the .pcap file as a blob
                .then(blob => {
                    // Create a download link for the .pcap file
                    const link = document.createElement('a');
                    const url = window.URL.createObjectURL(blob);  // Create a URL for the blob
                    link.href = url;

                    // Set the filename for the download
                    link.download = `${data.username}_session${data.session_number}.pcap`;

                    // Trigger the download by programmatically clicking the link
                    link.click();

                    // Clean up by revoking the object URL
                    window.URL.revokeObjectURL(url);
                })
                .catch(error => {
                    console.error('Error fetching .pcap file:', error);
                });
            } else {
                // Handle errors
                console.error("Error: ", result.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }

    return (
        <div className="saved-sessions-page-container">
            <div className="header">
                <h1>Saved Sessions</h1>
                <span className="user-name">Hello, {usercredentials.username}</span>
            </div>


            {/* The session list should be inside the saved-sessions-container */}
            <div className="saved-sessions-container">
                <ul className="saved-session-list">
                    {sessions.map((session) => (
                        <li
                            key={`${session.username}-${session.session_number}`} // Unique key for each session
                            className={`session-item ${selectedSession === session ? 'highlight' : ''}`}
                            onClick={() => handleViewDetails(session)} // Click to view details
                        >
                            <p>Session {session.session_number} - {new Date(session.session_date).toLocaleDateString()} - {session.captured_packets} packets</p>
                            <button onClick={() => {
                                // Call your existing download function here
                                downloadSession(usercredentials, session);
                            }}
                                className="download-button"
                                >
                                Download
                            </button>
                        </li>
                    ))}
                </ul>
            </div>
            <div className="bottom-saved-sessions-container">
                {selectedSession && (
                    <>
                    {/* Session Display Content */}
                    <div className="session-display-content">
                      <h2>Packet Information for Session {selectedSession.session_number}</h2>
                      {Array.isArray(capturedPackets) ? (
                        <ul>
                          {capturedPackets.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 for this session</p>
                      )}
                    </div>

                    {/* Packet Details Container */}
                    <div className="packet-details-sessions-container">
                      <h2>Session 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="back">
                    <p>
                        <Link to="/dashboard">Back To Dashboard</Link>
                    </p>
                </div>
        </div>
    );
}

export default SavedSessions;
