import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '../store/store';
import { removeFromCart, updateCartItem } from '../store/actions/cartActions';
import { useNavigate } from 'react-router-dom';

import {
  Typography,
  IconButton,
  Button,
  Divider,
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
  Paper,
  Grid,
  Box,
  Stack,
  Tooltip,
} from '@mui/material';
import {
  Delete as DeleteIcon,
  Add as AddIcon,
  Remove as RemoveIcon,
} from '@mui/icons-material';

const CartPage: React.FC = () => {
  const cartItems = useSelector((state: RootState) => state.cart.items);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const handleRemoveFromCart = (productId: number) => {
    dispatch(removeFromCart(productId));
  };

  const handleQuantityChange = (productId: number, quantity: number) => {
    dispatch(updateCartItem(productId, quantity));
  };

  const totalPrice = cartItems.reduce(
    (acc, item) => acc + item.product.price * item.quantity,
    0
  );

  return (
    <Box sx={{ mt: 4, px: { xs: 2, md: 4 } }}>
      <Typography variant="h4" gutterBottom>
        Корзина
      </Typography>
      {cartItems.length === 0 ? (
        <Typography variant="h6">Ваша корзина пуста</Typography>
      ) : (
        <Grid container spacing={4}>
          <Grid item xs={12} md={8}>
            <TableContainer component={Paper} sx={{ mb: 4 }}>
              <Table aria-label="cart table">
                <TableHead>
                  <TableRow>
                    <TableCell>Товар</TableCell>
                    <TableCell align="right">Цена</TableCell>
                    <TableCell align="center">Количество</TableCell>
                    <TableCell align="right">Итого</TableCell>
                    <TableCell align="center">Действия</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {cartItems.map((item) => (
                    <TableRow key={item.product.id}>
                      <TableCell component="th" scope="row">
                        <Stack direction="row" spacing={2} alignItems="center">
                          <img
                            src={item.product.image}
                            alt={item.product.name}
                            style={{ width: '60px', height: '60px', objectFit: 'cover' }}
                          />
                          <Typography variant="body1">
                            {item.product.name}
                          </Typography>
                        </Stack>
                      </TableCell>
                      <TableCell align="right">
                        {item.product.price.toLocaleString()} ₽
                      </TableCell>
                      <TableCell align="center">
                        <Box
                          sx={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                          }}
                        >
                          <IconButton
                            onClick={() =>
                              handleQuantityChange(
                                item.product.id,
                                item.quantity - 1
                              )
                            }
                            disabled={item.quantity <= 1}
                          >
                            <RemoveIcon />
                          </IconButton>
                          <Typography
                            variant="body1"
                            sx={{ mx: 1, minWidth: '24px', textAlign: 'center' }}
                          >
                            {item.quantity}
                          </Typography>
                          <IconButton
                            onClick={() =>
                              handleQuantityChange(
                                item.product.id,
                                item.quantity + 1
                              )
                            }
                          >
                            <AddIcon />
                          </IconButton>
                        </Box>
                      </TableCell>
                      <TableCell align="right">
                        {(item.product.price * item.quantity).toLocaleString()} ₽
                      </TableCell>
                      <TableCell align="center">
                        <Tooltip title="Удалить из корзины">
                          <IconButton
                            onClick={() => handleRemoveFromCart(item.product.id)}
                          >
                            <DeleteIcon color="error" />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </Grid>
          <Grid item xs={12} md={4}>
            <Paper sx={{ p: 3 }}>
              <Typography variant="h6" gutterBottom>
                Итого
              </Typography>
              <Divider sx={{ mb: 2 }} />
              <Stack direction="row" justifyContent="space-between" sx={{ mb: 1 }}>
                <Typography variant="body1">Сумма заказа:</Typography>
                <Typography variant="body1">{totalPrice.toLocaleString()} ₽</Typography>
              </Stack>
              {/* Если есть дополнительные сборы или скидки, их можно добавить здесь */}
              <Divider sx={{ mb: 2 }} />
              <Typography variant="h5" sx={{ fontWeight: 'bold', mb: 2 }}>
                Общая сумма: {totalPrice.toLocaleString()} ₽
              </Typography>
              <Button
                variant="contained"
                color="primary"
                fullWidth
                onClick={() => navigate('/checkout')}
              >
                Перейти к оформлению
              </Button>
            </Paper>
          </Grid>
        </Grid>
      )}
    </Box>
  );
};

export default CartPage; добавить возможность выбора товаров для оформелния