import React, { useState } from 'react';
import Title from '../components/Title';
import { actionOrder, clearCart } from '../api/api';
import CartGood from '../components/CartGood';
import { useDispatch, useSelector } from 'react-redux';
import { Box, Button } from '@mui/material';
import Price from '../components/Price';

export default function CartPage() {
  const goods = useSelector(state => state.cart.goods);
  const totalAmount = useSelector(state => state.cart.totalAmount);
  const dispatch = useDispatch();
  console.log(goods);
  const createOrder = (orderGoods) => {
    const orderGoodsDto = [];
    orderGoods.forEach(orderGood => {
      orderGoodsDto.push({
        good: {_id: orderGood.good._id},
        count: orderGood.count
      });
    });
    dispatch(actionOrder(orderGoodsDto));
  }
  return (
    <>
      <Title>Cart</Title>
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', m: '4px' }}>
        <Button
          variant="text"
          size='small'
          color='inherit'
          sx={{ maxWidth: '100px' }}
          onClick={() => dispatch(clearCart())}
        >
          Clear cart
        </Button>
      </Box>
      {goods?.map((good) =>
        <CartGood good={good} key={good.good._id} />)}
        <Price>{totalAmount}</Price>
        <Button onClick={() => createOrder(goods)}>Create order</Button>
    </>
  )
}
