import React, {useState} from 'react'
import { Box, Card, CardActions, CardContent, Collapse, Button, Typography, Rating, useTheme, useMediaQuery } from '@mui/material'
import { useGetProductsQuery } from 'state/api'
import Header from "components/Header"


const Product = ({ _id, name, description, price, rating, category, supply, stat}) => {
    const theme =useTheme();
    const [isexpanded, setIsExpanded] = useState(false);

    return(
        <Card sx={{backgroundImage: "none", backgroundColor: theme.palette.background.alt, borderRadius: "0.5rem"}}>
            <CardContent>
                <Typography sx={{fontSize: "14px"}} color={theme.palette.secondary[300]} gutterBottom>
                    {category}
                </Typography>
                <Typography variant='h5' component="div">
                    {name}
                </Typography>
                <Typography sx={{mb: "1.5rem"}} color={theme.palette.secondary[400]}>
                    ${Number(price).toFixed(2)}
                </Typography>
                <Rating value={rating} readOnly/>
                <Typography variant='body2'>
                    {description}
                </Typography>
            </CardContent>
            <CardActions>
                <Button onClick={() => setIsExpanded(!isexpanded)} variant='prinary' size='small'>More</Button>
            </CardActions>
            <Collapse in={isexpanded} timeout="auto" unmountOnExit sx={{color: theme.palette.neutral[300]}}>
                <CardContent>
                    <Typography>id: {_id}</Typography>
                    <Typography>Supply left: {supply}</Typography>
                    <Typography>Yealy sales This year: {stat.yaerlySalesTotal}</Typography>
                    <Typography>Yearly units sold this year:{stat.yaerlyTotalSoldUnit}</Typography>
                </CardContent>
            </Collapse>
        </Card>
    )
}



const Products = () => {
    const {data, isloading} = useGetProductsQuery();
    const nonMobile = useMediaQuery("(min-width: 800px)");



  return (
    <Box m="1.5rem 2.5rem">
        <Header title="Products" subtitle="List of products"/>
        {data || isloading ? (
            <Box mt="20px" display="grid" gridTemplateColumns="repeat(4, minmax(0, 1fr))" justifyContent="space-between" rowGap="20px" columnGap="1.5%" sx={{"& > div" : {gridColumn: nonMobile ? undefined : "span 4"}}}>
                {data.map(({_id, name, description, price, rating, category, supply, stat}) => (
                    <Product key={_id} _id={_id} name={name} description={description} price={price} rating={rating} category={category} supply={supply} stat={stat}/>
                ))}
            </Box>
        ) : <>Loading...</>}
    </Box>
  )
}

export default Products