import React, {useContext, useState} from 'react';
import {View, Text, StyleSheet, Button, Image} from 'react-native';
import {Colors} from '../../constants/Constants';
import {CartContext} from '../../store/CartContext';

const CartItem = ({item}) => {
  const {removeFromCart, updateQuantity} = useContext(CartContext);

  const handleRemoveFromCart = () => {
    removeFromCart(item.product);
  };

  const handleUpdateQuantity = newQuantity => {
    updateQuantity(item.product, newQuantity);
  };

  return (
    <View style={styles.itemContainer}>
      <View style={styles.imageContainer}>
        <Image source={item.product.image} style={styles.image} />
      </View>
      <View style={styles.detailContainer}>
        <Text>{item.product.name}</Text>
        <Text style={styles.price}>{item.product.price}</Text>
      </View>
      <View style={styles.qtyContainer}>
        <Button title="X" onPress={handleRemoveFromCart} />
        <Button
          title="-"
          onPress={() => handleUpdateQuantity(item.quantity - 1)}
        />
        <Text>{item.product.quantity}</Text>
        <Button
          style={styles.inc_dec_btn}
          title="+"
          onPress={() => handleUpdateQuantity(item.quantity + 1)}
        />
      </View>
    </View>
  );
};

const Cart = () => {
  const {cart} = useContext(CartContext);

  const calculateTotalPrice = () => {
    let total = 0;
    cart.map(item => {
      total += parseFloat(item.product.price) * parseInt(item.product.quantity);
    });
    return parseFloat(total);
  };

  return (
    <View style={styles.cartContiner}>
      {cart.map(item => (
        <CartItem key={item.product.id} item={item} />
      ))}
      <Text style={styles.title}>Total : {calculateTotalPrice()}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  cartContiner: {
    flex: 1,
  },
  itemContainer: {
    padding: 10,
    flexDirection: 'row',
    justifyContent: 'flex-start',
  },
  imageContainer: {
    flex: 1,
  },
  detailContainer: {
    flex: 3,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  qtyContainer: {
    flex: 2,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
    paddingBottom: 5,
  },
  name: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  quantity: {
    fontSize: 14,
    color: '#888',
  },
  image: {
    width: 40,
    height: 40,
  },
  price: {
    fontSize: 14,
    color: '#888',
  },
  inc_dec_btn: {
    borderRadius: 25,
    backgroundColor: Colors.primary500,
  },
});

export default Cart;
