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

export function IngredientList({rows, value, infoHandler, changeHandler, grouping}) {
    const [size, setSize] = useState(10);
    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 (
                        <IngredientCard row={row} key={row.id} value={value}
                                        changeHandler={changeHandler} infoHandler={infoHandler}/>
                    )
                })
        }

        const group = groupByForLoop(rows, "type")
        if (!group || group.size === 0) {
            return null;
        }
        const keys = Array.from(group.keys());
        keys.sort(getComparator("asc"))
            .forEach((key) => {
                const list = group.get(key)
                res.push(
                    <Accordion key={key}>
                        <AccordionSummary
                            expandIcon={<ExpandMoreIcon/>}
                            aria-controls="panel1-content"
                            id="panel1-header"
                        >
                            <Typography component="span">{key !== "null" ? key : "Без категории"}</Typography>
                        </AccordionSummary>
                        <AccordionDetails>
                            {list.sort(getComparator("asc", "name"))
                                .map((row) => {
                                    return (
                                        <IngredientCard row={row} key={row.id} value={value}
                                                        changeHandler={changeHandler} infoHandler={infoHandler}/>
                                    )
                                })}
                        </AccordionDetails>
                    </Accordion>
                )
            })
        return res;
        // eslint-disable-next-line
    }, [size, rows])

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