import {useMemo, useState} from "react";
import {getComparator} from "../core/getComparator";
import {Accordion, AccordionDetails, AccordionSummary} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import {CocktailListCard} from "./CocktailListCard";
import {groupByForLoop} from "../core/groupByForLoop";

export function CocktailsList({rows, grouping, changeHandler, infoHandler}) {
    const [size, setSize] = useState(20);

    window.addEventListener('scroll', () => {
        if (window.innerHeight + window.scrollY >= (document.documentElement.scrollHeight - 100)) {
            if (!grouping) {
                setSize(size + 10)
            }
        }
    });

    const visibleRows = useMemo(() => {
        let res = [];
        if (rows.length === 0) {
            return null;
        }
        if (!grouping) {
            return rows
                .sort(getComparator("asc", "name"))
                .slice(0, size)
                .map((row) => {
                    return (
                        <CocktailListCard row={row} key={row.id}
                                          changeHandler={changeHandler} infoHandler={infoHandler}/>
                    )
                })
        }

        const group = groupByForLoop(rows, "category")
        if (!group || group.size === 0) {
            return null;
        }
        Array.from(group.keys())
            .sort(getComparator())
            .map((key) => {
                const list = group.get(key);
                res.push(
                    <Accordion key={key} sx={{borderRadius: '5px', mb: 1}}>
                        <AccordionSummary
                            expandIcon={<ExpandMoreIcon/>}
                            aria-controls="panel1-content"
                            id="panel1-header"
                        >
                            <Typography component="span">{key}</Typography>
                        </AccordionSummary>
                        <AccordionDetails sx={{p: 1}}>
                            {list.sort(getComparator("asc", "name"))
                                .map((row) => {
                                    return (
                                        <CocktailListCard row={row} key={row.id}
                                                          changeHandler={changeHandler} infoHandler={infoHandler}/>
                                    )
                                })}
                        </AccordionDetails>
                    </Accordion>
                )
            })
        return res;
        // eslint-disable-next-line
    }, [size, rows])

    return (
        <Box mt={2}>
            {visibleRows}
        </Box>
    )
}