import { Stack, Typography, Box, CircularProgress } from '@mui/joy';
import { useParams } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from "../../store/hooks";
import { fetchNamedEntity, addToHistory } from "../../store/namedEntitySlice";
import { useEffect } from "react";
import NewsItemCard from './cards/NewsItemCard';
import NamedEntityChip from "./chips/NamedEntityChip";
import dayjs from "dayjs";

function Tag() {
    const { tag } = useParams();

    const namedEntityTag = useAppSelector((state) => state.namedEntity.namedEntity);
    const status = useAppSelector((state) => state.namedEntity.status);
    const dispatch = useAppDispatch();

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

    useEffect(() => {
        dispatch(addToHistory(namedEntityTag))
    }, [dispatch, tag, namedEntityTag])

    return (
        <div>
            {status === "loading" ?
                <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                    <CircularProgress thickness={1} />
                </Box>
                :
                <div>
                    <Typography level="h2" component="h1" sx={{ display: 'inline-flex', gap: 1.5, alignItems: "center", }}>
                        Tag 
                        {namedEntityTag.name ? 
                        <NamedEntityChip namedEntity={namedEntityTag} size="lg" /> 
                        : tag}
                    </Typography>

                    <Typography sx={{ marginTop: 1 }} level="h4" component="h4">
                        This tag has been created at {namedEntityTag.created_at ? dayjs(namedEntityTag.created_at).format('DD MMM YYYY HH:mm') : 'Unknown'}.
                    </Typography>

                    <Typography sx={{ marginTop: 2 }} level="body-md" component="p">
                        Tagged in {namedEntityTag.news_items ? namedEntityTag.news_items.length : 0} news articles listed below.
                    </Typography>

                    <Stack
                        sx={{ marginTop: 2, marginBottom: 2 }}
                        direction="column"
                        justifyContent="flex-start"
                        alignItems="stretch"
                        spacing={2}
                    >
                        {namedEntityTag.news_items &&
                            namedEntityTag.news_items.map((newsItem) => <NewsItemCard key={newsItem.id} newsItem={newsItem} />)}
                    </Stack>
                </div>}
        </div>
    );
}

export default Tag;