import { useEffect, useState } from 'react'
import { Card, Flex } from '@mantine/core';

function CardComponent({
  url,
  is_alive
}: { url: string, is_alive: boolean }) {
  return (
    <Card>
      <Flex p='sm' direction='column'>
        <p>{url}</p>
        <p>{JSON.stringify(is_alive)}</p>
      </Flex>
    </Card>
  )
}

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

  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>
      <Flex direction='column' gap='sm'>
        {servers.length > 0 && servers.map((server: { name: string, status: boolean }) => (
          <CardComponent url={server.name} is_alive={server.status} />
        ))}
      </Flex>
    </div>
  )
}