import React, { useEffect } from "react";
import { Box, CircularProgress, Typography, Stack } from "@mui/joy";
import { useAppSelector, useAppDispatch } from "../../store/hooks";
import { fetchNewsChannels } from "../../store/newsChannelSlice";
import NewsChannelCard from "./cards/NewsChannelCard";

function NewsChannels() {
    const newsChannels = useAppSelector((state) => state.newsChannel.all);
    const status = useAppSelector((state) => state.newsChannel.status);
    const dispatch = useAppDispatch();

    useEffect(() => {
        dispatch(fetchNewsChannels());
    }, [dispatch]);

    return (
        <div>
            <Typography level="h2" component="h1">
                News Channels
            </Typography>

            <Stack
                sx={{ marginTop: 2, marginBottom: 2 }}
                direction="row"
                justifyContent="flex-start"
                alignItems="stretch"
                spacing={2}
            >
                {newsChannels.map((newsChannel) => <NewsChannelCard key={newsChannel.id} newsChannel={newsChannel} />)}
            </Stack>
            {status === "loading" &&
                <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                    <CircularProgress thickness={1} />
                </Box>
            }
        </div>
    );
}

export default NewsChannels;