import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import AlertsList from './DocList';
import { Alert } from './DocList';
import { Sidebar } from '../Sidebar';
import RightSidebar from '../RightSidebar';
import { Message } from '../ChatInterface';

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [dialogueText, setDialogueText] = useState<Message[]>([]);

  useEffect(() => {
    const fetchAlerts = async () => {
      
      try {
        const response = await fetch("http://localhost:4004/doc_list", {
          method: "GET",
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log("Fetched data.record:", data.record);

        setAlerts(data.record);
      } catch (error) {
        console.error("Failed to fetch alerts:", error);
    }
    };

    fetchAlerts();
  }, []);

  const handleAlert = (alert: Alert) => {
    navigate(`/doc/${alert.id}`, { state: { alert } });
  };

  return (
    <div className="flex min-h-screen bg-gray-50">
        <aside className="w-64 flex-shrink-0 h-full">
            <Sidebar />
        </aside>

        <main className="flex-1 p-4 flex  w-full justify-center">
            
            <div className="flex-1 py-1 px-2 sm:px-2 lg:px-2">
                <div className="w-full">
                <h1 className="text-3xl font-bold text-gray-900 mb-4">Dashboard</h1>

                <div className="bg-white shadow rounded-lg p-6 mt-6">
                    <h2 className="text-xl font-semibold text-gray-900 mb-4">Security Alerts</h2>
                    <AlertsList alerts={alerts} onSelectAlert={handleAlert} />
                </div>
                </div>
            </div>
            
        </main>
        <aside className="w-1/4 bg-gray-100 py-3">
            <RightSidebar setDialogueText={setDialogueText} />
        </aside>
    </div>
    
  );
};

export default Dashboard;
