import { useParams } from "react-router-dom"
import CategoryOneMenu from "../CategoryOneMenu"
import { useState } from "react"
import CategoryOneBreadcrumbs from "../CategoryOneBreadcrumbs"
import { useGetCategoryQuery, useGetGoodCountQuery, useGetGoodFindQuery } from "../../store/categoriesApi"
import CardProduct from "../CardProduct"
import { Grid, MenuItem, Pagination, Select } from "@mui/material"


const CategoryOnePage = () => {
    let { catId } = useParams()
    const { data: categoryPayload = null, isLoading } = useGetCategoryQuery(catId)
    const category = categoryPayload ? Object.values(categoryPayload)[0] : null
    const [page, setPage] = useState(1);
    const [limit, setLimit] = useState(6)
    const [sortSelectIndex, setSortSelectIndex] = useState(1)
    const { data: goodCountPayload} = useGetGoodCountQuery({categoryId: catId })
    const goodCount = goodCountPayload ? Object.values(goodCountPayload)[0] : null

    const sortQeryArr = [
        {
            categoryId: catId,
            sort: {price: 1},
            skip: (page - 1) * limit, 
            limit
        },
        {
            categoryId: catId,
            sort: {price: -1},
            skip: (page - 1) * limit,
            limit
        },
        {
            categoryId: catId,
            sort: {name: 1},
            skip: (page - 1) * limit,
            limit
        },
        {
            categoryId: catId,
            sort: {createdAt: -1},
            skip: (page - 1) * limit,
            limit
        },
    ]
        // sort должен быть обьект вида {поле сортировки: 1 или -1} где 1 сортировка по возрастаниюб -1 по убыванию.
        // limit число от 1 до 100
        // categoryId обязательный параметр иначе вернет пустой массив goods

    const handleChange = (event, value) => {
        setPage(value);
    };
    const handleChangeSelect = (event) => {
        setSortSelectIndex(event.target.value);
    };

    const { data: payload = null } = useGetGoodFindQuery(sortQeryArr[sortSelectIndex - 1])
    const goods = payload ? Object.values(payload)[0] : null

    const CardProductRender = (product) => (
        <CardProduct
            key={product._id}
            product={product}
        />
    )

    return (
        isLoading ? <div> прелоадер </div> :
            <>
                <Grid container spacing={2} alignItems="stretch" >
                    <Grid item xs={12} sm={6} md={4} lg={3} align-self="stretch">
                         <CategoryOneMenu category={category?.subCategories} /> 
                    </Grid>
                    <Grid item xs={12} sm={6} md={8} lg={9} container spacing={2} >
                        <CategoryOneBreadcrumbs parentCategory={category?.parent} thisCategory={category} />
                        <Grid item xs={12} >
                            <Select 
                                value={sortSelectIndex}
                                onChange={handleChangeSelect}
                            >
                                <MenuItem value={1}>По цене вверх</MenuItem>
                                <MenuItem value={2}>По цене вниз</MenuItem>
                                <MenuItem value={3}>По названию</MenuItem>
                                <MenuItem value={4}>Вначале новые</MenuItem>
                            </Select>
                        </Grid>
                        {goods && goods.map(CardProductRender)}
                        <Grid item xs={12} >
                            <Pagination count={Math.ceil(goodCount/limit)} page={page} onChange={handleChange} color="primary" variant="outlined"
                                sx={{ '& *': { justifyContent: 'center' } }} />
                        </Grid>

                    </Grid>

                </Grid>
            </>

    )
}

export default CategoryOnePage

