export interface Alert {
  id: string;
  severity: string;
  type: string;
  message: string;
  date: string;
  vendor: string;
  identity: string;
}


interface Props {
  alerts: Alert[];
  onSelectAlert: (alert: Alert) => void;
}

const AlertsList: React.FC<Props> = ({ alerts, onSelectAlert }) => {

  const handleSelectAlert = async (alert: Alert) => {
    try {
      
        const response = await fetch("http://localhost:4004/alert_info", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ message_id: String(alert.id)}),
        });
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        } else {
          onSelectAlert(alert);
        }
    } catch (error) {
      console.error('Error fetching alert data:', error);
    }
  };
  return (
    <table className="min-w-full table-auto">
      <thead>
        <tr>
          <th className="px-4 py-2 text-left">SEVERITY</th>
          <th className="px-4 py-2 text-left">MESSAGE</th>
          <th className="px-4 py-2 text-left">DATE</th>
          <th className="px-4 py-2 text-left">VENDOR</th>
          <th className="px-4 py-2 text-left">IDENTITY</th>
        </tr>
      </thead>
      <tbody>
        {alerts.length === 0 ? (
          <tr>
            <td className="px-4 py-2 text-gray-500" colSpan={5}>
              No alerts to display
            </td>
          </tr>
        ) : (
          alerts.map(alert => (
            <tr
              key={alert.id}
              onClick={() => handleSelectAlert(alert)}
              className="hover:bg-gray-100 cursor-pointer"
            >
              <td className="px-4 py-2">{alert.severity}</td>
              <td className="px-4 py-2">{alert.message}</td>
              <td className="px-4 py-2">{alert.date}</td>
              <td className="px-4 py-2">{alert.vendor}</td>
              <td className="px-4 py-2">{alert.identity}</td>
            </tr>
          ))
        )}
      </tbody>
    </table>
  );
};

export default AlertsList;
