import Header from "../components/Header";
import Footer from "../components/Footer";
import Breadcrumb from "../components/Breadcrumbs";
import {
    Accordion,
    AccordionDetails,
    AccordionSummary, Box, Button,
    Card, CardActionArea, CardActions, CardContent, CardMedia,
    Container, Divider,
    Grid,
    Typography,
    useMediaQuery
} from "@mui/material";
import {connect} from "react-redux";
import {actionFullCatById, actionFullRootCats} from "../actions/ActionCategory";
import Link from "react-router-dom/es/Link";
import Page404 from "./404Page";
import Route from "react-router-dom/es/Route";
import Switch from "react-router-dom/es/Switch";
import {useEffect, useState} from "react";
import {backURL} from "../actions/PathDB";
import {actionCartAdd} from "../reducers/CartReducer";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import AddShoppingCartIcon from '@mui/icons-material/AddShoppingCart';
import {Pagination} from "@mui/material";


const CategoryItem = ({object: {_id, name, subCategories}={}}) => {
    const [expanded, setExpanded] = useState(false);

    const handleChange = (panel) => (event, isExpanded) => {
        setExpanded(isExpanded ? panel : false);
    };

    return (
        <>
            {subCategories === null || !subCategories ?
                <li>
                    <Link style={{textDecoration: 'none'}} to={`/catalog/category/${_id}`}>
                        <Typography
                            variant='body1'
                            color='#616161'
                            marginBottom='10px'
                        >
                            {name}
                        </Typography>
                    </Link>
                </li>
                :
                <li>
                    <Accordion style={{border: 'none', borderRadius: '0',marginTop: '-10px', boxShadow: 'none'}} expanded={expanded === 'panel1'} onChange={handleChange('panel1')}>
                        <AccordionSummary
                            sx={{padding: '0'}}
                            expandIcon={<ExpandMoreIcon />}
                            aria-controls="panel1bh-content"
                            id="panel1bh-header"
                        >
                            <Link style={{textDecoration: 'none'}} to={`/catalog/category/${_id}`}>
                                <Typography
                                    variant='body1'
                                    color='#616161'
                                    padding='0'
                                >
                                    {name}
                                </Typography>
                            </Link>
                        </AccordionSummary>
                        <AccordionDetails>
                            <ul style={{listStyle: 'none', padding: '0 0 0 10px', marginBottom: '10px'}}>
                                {subCategories && Object.values(subCategories).map(item =>
                                    <CategoryItem object={item}/>
                                )}
                            </ul>
                        </AccordionDetails>
                    </Accordion>
                </li>
            }
        </>
    )
}
const CategoryAside = ({category}) => {
    return (
        <Grid sx={{backgroundColor: '#fff', padding: '30px'}} xs={12} lg={3}>
            <Typography
                variant='h6'
                letterSpacing='3px'
                lineHeight='1.3em'
                marginBottom='20px'
            >
                PRODUCT CATEGORIES
            </Typography>
            <ul style={{listStyle: 'none', padding: '0'}}>
                {category && Object.values(category).map(item =>
                    <CategoryItem object={item}/>
                )}
            </ul>
        </Grid>
    )
}

const GoodCard = ({good:{_id, name, description, price, images}={}, onCartAdd}) => {
    return (
        <Grid xs={12} lg={4} item margin='20px 0'>
            <Card sx={{ maxWidth: 345, height: '100%', display: 'flex', flexDirection: 'column', margin: 'auto 20px'}}>
                <CardActionArea sx={{padding: '0', flexGrow: '1', position: 'relative'}}>
                    <Link to='/' style={{position: 'relative', textDecoration: 'none'}}>
                        <CardMedia sx={{marginBottom: '20px', marginTop: '20px'}}
                            component="img"
                            height="230"
                            image={`${backURL}/${images[0].url}`}
                            alt="Good title image"
                        />
                        <CardContent sx={{display: 'flex', flexDirection: 'column', height: '180px', justifyContent: 'space-between'}}>
                            <Typography
                                textAlign='center'
                                fontFamily='sarif'
                                letterSpacing='2px'
                                marginBottom='20px'
                                fontSize='19px'
                                sx={{textTransform: 'uppercase', flexGrow: '1'}}
                                color='#000'
                            >
                               {name}
                            </Typography>
                            <Typography textAlign='center' variant="body2" color='#616161' marginBottom='20px' sx={{ flexGrow: '0'}}>
                                {description.length > 60 ?
                                    'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' :
                                    description
                                }
                            </Typography>
                            <Typography textAlign='center' variant="h5" color="#000" sx={{ flexGrow: '0'}}>
                                $ {parseFloat(price).toFixed(2)}
                            </Typography>
                        </CardContent>
                    </Link>
                </CardActionArea>
                <CardActions sx={{flexGrow: '0', justifyContent: 'space-between'}}>
                    <Button onClick={() => onCartAdd({_id, name, price, images})} size="small" color="primary">
                        <AddShoppingCartIcon />
                    </Button>
                    <Button onClick={() => console.log('nice')} size="small" color="primary">
                        <FavoriteBorderIcon />
                    </Button>
                </CardActions>
            </Card>
        </Grid>
    )
}
const CGoodCard = connect(null, {onCartAdd: actionCartAdd})(GoodCard)

const Goods = ({_id='5dc49f4d5df9d670df48cc64', category={}}) => {
    // const itemsPerPage = 6
    // const [page, setPage] = useState(1)
    // const [count, setCount] = useState(1)
    // const handleChange = (event, value) => {
    //     setPage(value);
    // }
   return (
       <>
           {(Object.values(category) || []).map(item => {
               if (item['_id'] === _id) {
                   if(!item.goods || item['goods'] === null) {
                       return <div>not info</div>
                   }
                   if (item.goods) {
                       // setCount(item['goods'].length / itemsPerPage)
                       return (item['goods'] || []).map((good, index) => <CGoodCard key={index} good={good}/>)
                   }
               }
               else if(item['subCategories'] !== null) {
                   return (item['subCategories'] || []).map(subItem => {
                       if (subItem['_id'] === _id) {
                           if(subItem['goods'] === null) return <div>not info</div>
                           // setCount(subItem['goods'].length / itemsPerPage)
                           return (subItem['goods'] || []).map(good => <CGoodCard good={good}/>)
                       }
                       else if(subItem['subCategories'] !== null) {
                           return (subItem['subCategories'] || []).map(subSubItem => {
                               if (subSubItem['_id'] === _id) {
                                   if(subSubItem['goods'] === null) return <div>not info</div>
                                   // setCount(subSubItem['goods'].length / itemsPerPage)
                                   return (subSubItem['goods'] || []).map(good => <CGoodCard good={good}/>)
                               }
                           })
                       }
                   })
               }
           })}
           {/*<Divider />*/}
           {/*<Box display='flex' justifyContent='center' width='100%'>*/}
           {/*    <Pagination*/}
           {/*        count={count}*/}
           {/*        page={page}*/}
           {/*        onChange={handleChange}*/}
           {/*        defaultPage={1}*/}
           {/*        color="primary"*/}
           {/*        size="large"*/}
           {/*        showFirstButton*/}
           {/*        showLastButton*/}
           {/*    />*/}
           {/*</Box>*/}
       </>
   )
}
const CGoods = connect(state => ({category: state.category}))(Goods)

const BlockGood = ({match:{params:{_id}}, getData}) => {
    useEffect(() => {
        getData(_id)
    },[_id, getData])
    return(
        <Grid container justifyContent='space-between'>
            <CGoods _id={_id} />
        </Grid>
    )
}
export const CBlockGood= connect(null, {getData: actionFullCatById})(BlockGood)

const Products = () => {
    return (
        <Grid xs={12} lg={9}>
            <Switch>
                <Route path="/catalog/category/:_id" component={CBlockGood} />
                <Route path="*" component={Page404} />
            </Switch>
        </Grid>
    )
}

const CatalogPage = ({category={}, actionRootCat}) => {
    const matches = useMediaQuery('(max-width:899px)')
    if(Object.entries(category).length === 0) actionRootCat()

    return (
        <>
            <Breadcrumb links={['catalog']}/>
            <main style={{backgroundColor: "#f3f3f3", padding: matches ? "20px 0" : "50px 0"}}>
                <Container maxWidth="lg">
                    <Grid container justifyContent='space-between'>
                        <CategoryAside category={category}/>
                        <Products/>
                    </Grid>
                </Container>
            </main>
        </>
    )
}
const CCatalogPage = connect(state => ({category: state.category}), {actionRootCat: actionFullRootCats})(CatalogPage)

export default CCatalogPage
