import { useEffect, useState } from 'react'
import { Card, Stack } from '@mui/material';

function CardComponent({
  url,
  is_alive
}: { url: any, is_alive: any }) {
  return (
    <Card>
      <Stack p='24px' direction='column'>
        <p>{url}</p>
        <p>{JSON.stringify(is_alive)}</p>
      </Stack>
    </Card>
  )
}

export default function MonitorPage() {
  const [servers, setServers] = useState<any>([])

  useEffect(() => {
    const eventSource = new EventSource(`${import.meta.env.VITE_API_MONITOR_URL}/watch`);

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      setServers(data)
    }

    eventSource.onerror = (error) => {
      console.error('Error with SSE connection:', error)
      eventSource.close()
    }

    return () => {
      eventSource.close()
    };
  }, [])

  return (
    <div>
      <Stack direction='column' spacing={1}>
        {servers.length > 0 && servers.map((server: any) => (
          <CardComponent url={server.name} is_alive={server.status} />
        ))}
      </Stack>
    </div>
  )
}