import Breadcrumb from "../components/Breadcrumbs";
import {connect} from "react-redux";
import {actionCardChange, actionCardClear, actionCardRemove} from "../reducers/CartReducer";
import {ActionFullOrder, ActionOrder} from "../actions/ActionOrder";
import {Box, Button, Container, Divider, Grid, Typography, useMediaQuery} from "@mui/material";
import {ItemHeaderLine, LinkProductItem, RemoveFromList, TableLine} from "../components/TableLine";
import {NotFoundBlock} from "../components/NotFoundBlock";
import imgUrl from "../img/not-found/3.png";
import AddShoppingCartIcon from "@mui/icons-material/AddShoppingCart";
import {SetCount} from "../components/SetCount";
import {useEffect, useState} from "react";

const CartGoodLine = ({item, onCartRemove, onCardChange}) => {
    let [count, setCount] = useState(item?.count)
    useEffect(() => {
        onCardChange(item?.good, count)
    }, [count])
    return(
        <Grid container alignItems='center' marginBottom='20px'>
            <Grid item xs={6}>
                <LinkProductItem item={[item?.good?._id, item?.good?.name, item?.good?.images]} children={<Typography>${item?.good?.price}</Typography>}/>
            </Grid>
            <Grid item xs={3} display='flex' justifyContent="center">
                <SetCount height={40} width={40} defaultValue={item?.count} onCount={value => setCount(value)}/>
            </Grid>
            <Grid item xs={2}>
                <ItemHeaderLine align={'center'} text={(`$${parseFloat(item?.good?.price * count).toFixed(2)}`) || 'NaN'}/>
            </Grid>
            <Grid item xs={1}>
                <RemoveFromList good={item?.good} onRemove={onCartRemove}/>
            </Grid>
        </Grid>
    )
}

const TotalPriceLine = ({title, subtitle, sizeSubtitle='body2'}) => {
    return (
        <Grid container display='flex' flexDirection='row' justifyContent='space-between' alignItems='center' padding='20px'>
            <Grid item xs={6}>
                <Typography
                    variant='body2'
                    color='#616161'
                    textAlign='left'
                >
                    {title}
                </Typography>
            </Grid>
            <Grid item xs={6}>
                <Typography
                    variant={sizeSubtitle}
                    color='#000'
                    textAlign='right'
                >
                    {subtitle}
                </Typography>
            </Grid>
        </Grid>
    )
}

const CartPage = ({cart, onCardChange, onCartClear, onCartRemove, onOrderUpsert}) => {
    const matches = useMediaQuery('(max-width:768px)')
    let rows = []
    for (const key of Object.values(cart)) {
        rows.push(key)
    }
    return (
        <>
            <Breadcrumb links={['cart']}/>
            {Object.values(cart).length > 0 ?
                <main style={{backgroundColor: "#f3f3f3", padding: matches ? "20px 0" : "50px 0", minHeight:'300px'}}>
                        <Container maxWidth="lg">
                            <Grid container justifyContent='space-between'>
                                <Grid item xs={8.5}>
                                    <TableLine columnName={['PRODUCT', 'QUANTITY', 'REMOVE', 'SUBTOTAL']} customSizeCol={[6, 3, 2, 1]}/>
                                    <Divider sx={{marginBottom: '20px'}}/>
                                    {rows.map(item => <CartGoodLine item={item} onCartRemove={onCartRemove} onCardChange={onCardChange}/>)}
                                    <Divider/>
                                </Grid>
                                <Grid item xs={3} sx={{backgroundColor: '#fff'}} height='100%' paddingBottom='20px'>
                                    <Typography
                                        padding='20px'
                                        variant='h4'
                                        fontFamily='sarif'
                                        letterSpacing='2px'
                                        textAlign='center'
                                    >
                                        TOTAL
                                    </Typography>
                                    <Divider/>
                                    <TotalPriceLine title={`${rows.length || 1} goods for the amount`} subtitle={`$${rows.reduce((a, i) => a + (i.good.price * i.count), 0)}`}/>
                                    <TotalPriceLine title={'Cost of delivery'} subtitle={'according to the carrier\'s tariffs'}/>
                                    <Divider/>
                                    <TotalPriceLine title={'To pay'} subtitle={`$${rows.reduce((a, i) => a + (i.good.price * i.count), 0)}`} sizeSubtitle={'h6'}/>
                                    <Divider sx={{marginBottom: '20px'}}/>
                                    <Box display='flex' justifyContent='center' flexDirection='column' alignItems='center'>
                                        <Button sx={{borderRadius: '0', width:'80%', padding: '10px 20px', marginBottom: '20px'}}
                                                color='success'
                                                variant="outlined"
                                                onClick={() => onOrderUpsert(cart)}
                                        >
                                            confirm the order
                                        </Button>
                                        <Button sx={{borderRadius: '0', width:'80%', padding: '10px 20px'}}
                                                color='warning'
                                                variant="outlined"
                                                onClick={() => onCartClear()}
                                        >
                                            cart clear
                                        </Button>
                                    </Box>
                                </Grid>
                            </Grid>
                        </Container>
                </main>:
                <NotFoundBlock img={imgUrl} headerText={'YOUR CART IS CURRENTLY EMPTY'} text={<Box display='flex' alignItems='center'><Typography component='span'>Click the</Typography><AddShoppingCartIcon sx={{margin: '0 10px'}}/><Typography component='span'>icons to add products</Typography></Box>}/>
            }
        </>
    )
}
const CCartPage = connect(state=>({cart: state.cart}), {onCardChange: actionCardChange, onCartClear: actionCardClear, onCartRemove: actionCardRemove, onOrderUpsert: ActionFullOrder})(CartPage)
export default CCartPage
