import React, {useRef, useState, useEffect} from 'react';
import {
  StyleSheet,
  Text,
  View,
  SafeAreaView,
  TouchableOpacity,
  FlatList,
  Image,
  Dimensions,
} from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Ionicons from 'react-native-vector-icons/Ionicons';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {useNavigation} from '@react-navigation/native';

const {width, height} = Dimensions.get('window');

// Banner Images
const originalImages = [
  {id: '1', image: require('../../assets/images/cafebanner/cafebanner1.jpg')},
  {id: '2', image: require('../../assets/images/cafebanner/cafebanner2.jpg')},
  {id: '3', image: require('../../assets/images/cafebanner/cafebanner3.jpg')},
  {id: '4', image: require('../../assets/images/cafebanner/cafebanner4.jpg')},
  {id: '5', image: require('../../assets/images/cafebanner/cafebanner5.jpg')},
];

const images = [
  originalImages[originalImages.length - 1],
  ...originalImages,
  originalImages[0],
];

// Categories
const categories = ['Full Menu', 'Vegetarian', 'Vegan', 'Non-Vegetarian'];

// Food items
const foodItems = [
  {
    id: '1',
    image: require('../../assets/images/cafebanner/cafebanner1.jpg'),
    name: 'Burger',
    category: 'Vegetarian',
    price: 8.99,
  },
  {
    id: '2',
    image: require('../../assets/images/cafebanner/cafebanner2.jpg'),
    name: 'Pizza',
    category: 'Vegetarian',
    price: 12.99,
  },
  {
    id: '3',
    image: require('../../assets/images/cafebanner/cafebanner3.jpg'),
    name: 'Fries',
    category: 'Vegan',
    price: 4.99,
  },
  {
    id: '4',
    image: require('../../assets/images/cafebanner/cafebanner5.jpg'),
    name: 'Sandwich',
    category: 'Vegetarian',
    price: 7.5,
  },
  {
    id: '5',
    image: require('../../assets/images/cafebanner/cafebanner4.jpg'),
    name: 'Salad',
    category: 'Vegan',
    price: 9.99,
  },
  {
    id: '6',
    image: require('../../assets/images/cafebanner/cafebanner1.jpg'),
    name: 'Pasta',
    category: 'Vegetarian',
    price: 10.99,
  },
  {
    id: '7',
    image: require('../../assets/images/cafebanner/cafebanner2.jpg'),
    name: 'Chicken Wrap',
    category: 'Non-Vegetarian',
    price: 11.5,
  },
  {
    id: '8',
    image: require('../../assets/images/cafebanner/cafebanner3.jpg'),
    name: 'Grilled Chicken',
    category: 'Non-Vegetarian',
    price: 13.99,
  },
];

const Cafe = () => {
  const navigation = useNavigation();
  const flatListRef = useRef();
  const [index, setIndex] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState('Full Menu');
  const [cartItems, setCartItems] = useState([]);

  const cartItemCount = cartItems.reduce(
    (total, item) => total + item.quantity,
    0,
  );

  // Calculate total amount
  const totalAmount = cartItems
    .reduce((total, item) => total + item.price * item.quantity, 0)
    .toFixed(2);

  useEffect(() => {
    flatListRef.current.scrollToIndex({index: 1, animated: false});
    const timer = setInterval(() => {
      setIndex(prev => {
        const nextIndex = prev + 1;
        flatListRef.current.scrollToIndex({index: nextIndex, animated: true});
        return nextIndex;
      });
    }, 5000);
    return () => clearInterval(timer);
  }, []);

  const onScrollEnd = e => {
    const offset = e.nativeEvent.contentOffset.x;
    let i = Math.round(offset / width);

    if (i === 0) {
      i = originalImages.length;
      flatListRef.current.scrollToIndex({index: i, animated: false});
    } else if (i === images.length - 1) {
      i = 1;
      flatListRef.current.scrollToIndex({index: i, animated: false});
    }

    setIndex(i);
  };

  const isItemInCart = itemId => {
    return cartItems.some(item => item.id === itemId);
  };

  const getItemQuantity = itemId => {
    const item = cartItems.find(cartItem => cartItem.id === itemId);
    return item ? item.quantity : 0;
  };

  const handleAddToCart = item => {
    const updatedCartItems = (() => {
      const existingItem = cartItems.find(cartItem => cartItem.id === item.id);
      if (existingItem) {
        return cartItems.map(cartItem =>
          cartItem.id === item.id
            ? {...cartItem, quantity: cartItem.quantity + 1}
            : cartItem,
        );
      } else {
        return [...cartItems, {...item, quantity: 1}];
      }
    })();
    setCartItems(updatedCartItems);
  };

  const handleIncreaseQuantity = itemId => {
    setCartItems(prevItems =>
      prevItems.map(item =>
        item.id === itemId ? {...item, quantity: item.quantity + 1} : item,
      ),
    );
  };

  const handleDecreaseQuantity = itemId => {
    setCartItems(prevItems => {
      const updatedItems = prevItems
        .map(item => {
          if (item.id === itemId) {
            const newQuantity = item.quantity - 1;
            if (newQuantity <= 0) {
              return null; // Mark for removal
            }
            return {...item, quantity: newQuantity};
          }
          return item;
        })
        .filter(Boolean); // Remove null items

      return updatedItems;
    });
  };

  const renderCarouselItem = ({item}) => (
    <View style={styles.imageContainer}>
      <Image source={item.image} style={styles.image} resizeMode="cover" />
    </View>
  );

  const filteredItems =
    selectedCategory === 'Full Menu'
      ? foodItems
      : foodItems.filter(item => item.category === selectedCategory);

  const renderFoodItem = ({item}) => {
    const quantity = getItemQuantity(item.id);
    const isInCart = isItemInCart(item.id) && quantity > 0;

    return (
      <View style={styles.cardWrapper}>
        <View style={styles.card}>
          <Image source={item.image} style={styles.cardImage} />
          <TouchableOpacity style={styles.heartIcon}>
            <AntDesign name="hearto" size={16} color="#fff" />
          </TouchableOpacity>
          <View style={styles.cardContent}>
            <View style={styles.namePriceRow}>
              <Text style={styles.foodName} numberOfLines={1}>
                {item.name}
              </Text>
              <Text style={styles.foodPrice}>£{item.price.toFixed(2)}</Text>
            </View>

            {isInCart ? (
              <View style={styles.quantityControls}>
                <TouchableOpacity
                  style={styles.quantityBtn}
                  onPress={() => handleDecreaseQuantity(item.id)}>
                  <AntDesign name="minus" size={14} color="#fff" />
                </TouchableOpacity>

                <Text style={styles.quantityText}>{quantity}</Text>

                <TouchableOpacity
                  style={styles.quantityBtn}
                  onPress={() => handleIncreaseQuantity(item.id)}>
                  <AntDesign name="plus" size={14} color="#fff" />
                </TouchableOpacity>
              </View>
            ) : (
              <TouchableOpacity
                style={styles.addBtn}
                onPress={() => handleAddToCart(item)}>
                <Text style={styles.addBtnText}>Add to Cart</Text>
              </TouchableOpacity>
            )}
          </View>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <AntDesign name="arrowleft" size={28} color="#000" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Cafe Menu</Text>
        <TouchableOpacity
          style={styles.cartIconContainer}
          onPress={() => navigation.navigate('Cart', {cartItems})}>
          <Ionicons name="cart-outline" size={26} color="#000" />
          {cartItemCount > 0 && (
            <View style={styles.cartBadge}>
              <Text style={styles.cartBadgeText}>{cartItemCount}</Text>
            </View>
          )}
        </TouchableOpacity>
      </View>

      <View style={styles.carouselContainer}>
        <FlatList
          ref={flatListRef}
          data={images}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          renderItem={renderCarouselItem}
          keyExtractor={(_, i) => i.toString()}
          onMomentumScrollEnd={onScrollEnd}
          getItemLayout={(_, i) => ({
            length: width,
            offset: width * i,
            index: i,
          })}
        />
      </View>

      <View style={styles.mainContentContainer}>
        <View style={styles.panel}>
          <View style={styles.panelHeader}>
            <Image
              source={require('../../assets/images/side_Logo.png')}
              style={styles.logo}
            />
            <Text style={styles.description}>
              Delicious meals prepared with fresh ingredients
            </Text>

            <View style={styles.stars}>
              {[1, 2, 3, 4, 5].map(star => (
                <FontAwesome key={star} name="star" size={16} color="#c3841a" />
              ))}
            </View>

            <View style={styles.categoryRow}>
              {categories.map(cat => (
                <TouchableOpacity
                  key={cat}
                  style={[
                    styles.categoryBtn,
                    selectedCategory === cat && styles.categoryBtnSelected,
                  ]}
                  onPress={() => setSelectedCategory(cat)}>
                  <Text
                    style={[
                      styles.categoryText,
                      selectedCategory === cat && styles.categoryTextSelected,
                    ]}>
                    {cat}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          <FlatList
            data={filteredItems}
            keyExtractor={item => item.id}
            numColumns={2}
            showsVerticalScrollIndicator={false}
            columnWrapperStyle={styles.columnWrapper}
            contentContainerStyle={styles.foodGridContainer}
            renderItem={renderFoodItem}
          />
        </View>
      </View>

      {/* Footer that appears when items are in cart */}
      {cartItemCount > 0 && (
        <View style={styles.footer}>
          <View style={styles.footerContent}>
            <View style={styles.footerTextContainer}>
              <Text style={styles.footerItemCount}>
                {cartItemCount} {cartItemCount === 1 ? 'Item' : 'Items'}
              </Text>
              <Text style={styles.footerTotalAmount}>
                Total: £ {totalAmount}
              </Text>
            </View>
            <TouchableOpacity
              style={styles.viewCartButton}
              onPress={() => navigation.navigate('Cart', {cartItems})}>
              <Text style={styles.viewCartButtonText}>View Cart</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: '#fff'},
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingBottom: 12,
    paddingTop: 15,
    backgroundColor: '#fff',
  },
  headerTitle: {fontSize: 19, color: '#000'},
  cartIconContainer: {position: 'relative'},
  cartBadge: {
    position: 'absolute',
    top: -6,
    right: -10,
    backgroundColor: 'red',
    borderRadius: 10,
    paddingHorizontal: 5,
    paddingVertical: 1,
  },
  cartBadgeText: {color: '#fff', fontSize: 12, fontWeight: 'bold'},
  carouselContainer: {height: 200},
  imageContainer: {width: width},
  image: {width: width, height: 200},
  mainContentContainer: {
    flex: 1,
    marginHorizontal: 15,
    marginTop: 20,
    marginBottom: 7,
  },
  panel: {
    flex: 1,
    backgroundColor: '#fff',
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    marginTop: -60,
    paddingTop: 15,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: -5},
    shadowOpacity: 0.1,
    shadowRadius: 10,
    elevation: 10,
  },
  panelHeader: {
    paddingHorizontal: 5,
    marginBottom: 10
  },
  logo: {
    width: 120,
    height: 50,
    alignSelf: 'center',
    paddingBottom: 15,
  },
  description: {
    textAlign: 'center',
    color: '#666',
    marginBottom: 10,
    fontSize: 14,
  },
  stars: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginBottom: 15,
  },
  categoryRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
    marginBottom: 5,
  },
  categoryBtn: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 20,
    paddingVertical: 6,
    paddingHorizontal: 24,
    backgroundColor: '#f9f9f9',
    margin: 5,
  },
  categoryBtnSelected: {
    backgroundColor: '#c3841a',
    borderColor: '#c3841a',
  },
  categoryText: {
    color: '#666',
    fontWeight: '500',
    fontSize: 14,
  },
  categoryTextSelected: {
    color: '#fff',
  },
  foodGridContainer: {
    paddingBottom: 100,
    paddingHorizontal: 10,
  },
  columnWrapper: {
    justifyContent: 'space-between',
    marginBottom: 15,
  },
  cardWrapper: {
    width: '48%',
  },
  card: {
    backgroundColor: '#fdfdfd',
    borderRadius: 12,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 3,
  },
  cardImage: {
    width: '100%',
    height: 120,
  },
  heartIcon: {
    position: 'absolute',
    top: 8,
    right: 8,
    backgroundColor: '#00000088',
    borderRadius: 20,
    padding: 5,
  },
  cardContent: {padding: 10},
  namePriceRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  foodName: {
    fontWeight: 'bold',
    fontSize: 16,
    color: '#333',
    flex: 1,
    marginRight: 5,
  },
  foodPrice: {
    color: '#c3841a',
    fontWeight: 'bold',
    fontSize: 15,
  },
  addBtn: {
    backgroundColor: '#c3841a',
    paddingVertical: 6,
    borderRadius: 6,
    alignItems: 'center',
  },
  addBtnText: {
    color: '#fff',
    fontWeight: 'bold',
  },
  quantityControls: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  quantityBtn: {
    backgroundColor: '#c3841a',
    padding: 6,
    borderRadius: 6,
  },
  quantityText: {
    marginHorizontal: 8,
    fontWeight: 'bold',
    fontSize: 15,
    color: '#333',
  },
  footer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#eee',
    paddingTop: 15,
    paddingBottom: 20,
    paddingHorizontal: 20,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: -2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 5,
  },
  footerContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  footerTextContainer: {
    flex: 1,
  },
  footerItemCount: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
  },
  footerTotalAmount: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#c3841a',
  },
  viewCartButton: {
    backgroundColor: '#c3841a',
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 8,
  },
  viewCartButtonText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 16,
  },
});

export default Cafe;
