/**
 * @file PublicPresetsPage.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

import {axiosGet, axiosPost} from "../../services/AxiosService";
import React, {useEffect, useState} from "react";
import {Grid} from "@mui/material";
import {useAuth} from "../../services/AuthMiddleware";
import PublicPreset from "../../components/presets/PublicPreset";
import {useNavigate} from "react-router-dom";
import FilterComponent, {Types} from "../../components/common/FilterComponent";
import CenteredCircularProgress from "../../components/common/CenteredCircularProgress";
import Paginator from "../../components/common/Paginator";

function PublicPresetsPage() {
    const [presets, setPresets] = useState({});
    const [showAll, setShowAll] = useState(true);
    const [ownerFilter, setOwnerFilter] = useState("");
    const [nameFilter, setNameFilter] = useState("");
    const [isLoading, setLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(5);
    const [pageCount, setPageCount] = useState(1);
    const [totalItemCount, setTotalItemCount] = useState(0);
    const navigate = useNavigate();
    const auth = useAuth();

    const FILTER_OBJ = [
        {id: "newPreset", name: "Nové přednastavení", type: Types.BUTTON, fce: () => createNewPreset()},
        {id: "all", name: "Všechna přednastavení", type: Types.BOOLEAN, defValue: true, fce: setShowAll},
        {id: "name", name: "Název", type: Types.STRING, defValue: null, fce: (str) => setNameFilter(str)},
        {id: "owner", name: "Uživatel", type: Types.STRING, defValue: null, fce: (str) => setOwnerFilter(str)},

        {id: "perPage", name: "Na stránce", type: Types.SELECT, defValue: 5, fce: (val) => setItemsPerPage(val),
            items: [
                {val: 1, name: "1"},
                {val: 2, name: "2"},
                {val: 3, name: "3"},
                {val: 4, name: "4"},
                {val: 5, name: "5"},
                {val: 10, name: "10"},
                {val: 15, name: "15"},
                {val: 25, name: "25"},
                {val: 50, name: "50"}
            ]
        },
    ]

    useEffect(() => {
        setLoading(true);
        let filter = {data: true, owners: true};
        if (ownerFilter !== "" && ownerFilter !== null && ownerFilter !== undefined) {
            filter["owner"] = ownerFilter;
        }
        if (nameFilter !== "" && nameFilter !== null && nameFilter !== undefined) {
            filter["name"] = nameFilter;
        }

        filter["max_items"] = itemsPerPage;
        filter["page"] = page - 1;

        axiosGet("/presets" + (showAll ? "" : "/my"), filter)
            .then((res) => {
                setTotalItemCount(res.data.count);
                setPresets(res.data.items);
                setLoading(false);
            }).catch((e) => {
            console.error(e);
        });
    }, [showAll, nameFilter, ownerFilter, page, itemsPerPage]);

    useEffect(() => {
        const cnt = Math.ceil(totalItemCount/itemsPerPage);
        setPageCount(cnt);
    }, [totalItemCount, itemsPerPage]);

    useEffect(() => {
        if (page !== 1) {
            setPage(1);
        }
    }, [nameFilter, ownerFilter]);

    const createNewPreset = async () => {
        const res = await axiosPost("/presets", {
            ownerID: auth.user.id,
            name: "Nový preset",
            shortDescription: "Popis",
            description: "Dlouhý popis",
        });
        navigate("/presets/" + res.data.id);
    }

    return (<>
        <FilterComponent entries={FILTER_OBJ}/>

        {isLoading ?
            <CenteredCircularProgress/>
            :
            <Grid container columns={{xs: 1, sm: 2, md: 3, lg: 4}} spacing={2}>
                {Array.from(presets).map((preset, _) => {
                    return <Grid item xs={1} key={preset.id}>
                               <PublicPreset preset={preset}/>
                           </Grid>;
                })}
            </Grid>
        }

        <Paginator page={page} pageCount={pageCount} pageChanged={(val) => setPage(val)} bottomPinned={true}/>
    </>);
}


export default PublicPresetsPage