import React, { useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { getStyles } from './cartScreen.styles';
import { Header, QuantitySelector, PrimaryButton } from '@components';
import { useAppTheme } from '@theme';
import {
  selectCartTotal,
  getCartThunk,
  updateCartItemThunk,
} from '../../../store/commonreducers/cart';
import { AppStackParamList } from '../../../navigation/appStack';
import { useAppDispatch, useAppSelector } from '@store';
import { getFullUrl } from '../../../utils/helper';
// import { getFullUrl } from '@utils/helperr';

type CartScreenNavProp = StackNavigationProp<AppStackParamList, 'CartScreen'>;

export const CartScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const dispatch = useAppDispatch();
  const navigation = useNavigation<CartScreenNavProp>();
  const { items, isLoading } = useAppSelector(state => state.cart);
  const totals = useAppSelector(selectCartTotal);

  useEffect(() => {
    dispatch(getCartThunk());
  }, [dispatch]);

  if (!isLoading && items.length === 0) {
    return (
      <View style={styles.container}>
        <Header title="Cart" onBack={() => navigation.goBack()} />
        <View style={styles.emptyWrap}>
          <Text style={styles.emptyEmoji}>🛒</Text>
          <Text style={styles.emptyTitle}>Your cart is empty</Text>
          <Text style={styles.emptySubtitle}>
            Looks like you haven't added anything yet. Browse providers and find
            something you'll love.
          </Text>
          <TouchableOpacity
            style={styles.emptyButton}
            activeOpacity={0.85}
            onPress={() => navigation.goBack()}
          >
            <Text style={styles.emptyButtonText}>Start Ordering</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Header title="Cart" onBack={() => navigation.goBack()} />

      <ScrollView
        contentContainerStyle={styles.list}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.etaBanner}>
          <Text style={styles.etaIcon}>🛵</Text>
          <Text style={styles.etaText}>Delivery in 20–25 mins</Text>
        </View>

        <View style={styles.itemsCard}>
          {items.map((item, index) => (
            <View
              key={item.id}
              style={[
                styles.cartItem,
                index < items.length - 1 && styles.cartItemDivider,
              ]}
            >
              <Image
                style={styles.itemThumb}
                source={{ uri: getFullUrl(item.product.imageUrl) }}
              />
              <View style={styles.itemInfo}>
                <Text style={styles.itemTitle} numberOfLines={2}>
                  {item.product.name}
                </Text>
                <Text style={styles.itemPrice}>₹{item.product.price}</Text>
              </View>
              <QuantitySelector
                value={item.quantity}
                onIncrement={() =>
                  dispatch(
                    updateCartItemThunk({
                      productId: item.productId,
                      quantity: item.quantity + 1,
                    }),
                  )
                }
                onDecrement={() => {
                  if (item.quantity >= 1) {
                    dispatch(
                      updateCartItemThunk({
                        productId: item.productId,
                        quantity: item.quantity - 1,
                      }),
                    );
                  }
                }}
              />
            </View>
          ))}
        </View>

        <TouchableOpacity
          style={styles.addMoreRow}
          activeOpacity={0.7}
          onPress={() => navigation.goBack()}
        >
          <Text style={styles.addMoreIcon}>+</Text>
          <Text style={styles.addMoreText}>Add more items</Text>
        </TouchableOpacity>

        <View style={styles.footer}>
          {/* Coupon logic removed/commented out for now as requested
          <Text style={styles.sectionTitle}>Apply Coupon</Text>
          <View style={styles.couponCard}>
            ...
          </View>
          */}

          <Text style={styles.sectionTitle}>Bill Details</Text>
          <View style={styles.billCard}>
            <View style={styles.feeRow}>
              <Text style={styles.feeLabel}>Subtotal</Text>
              <Text style={styles.feeValue}>₹{totals.subtotal}</Text>
            </View>
            <View style={styles.feeRow}>
              <Text style={styles.feeLabel}>Delivery Fee</Text>
              <Text style={styles.feeValue}>₹{totals.deliveryFee}</Text>
            </View>
            <View style={styles.feeRow}>
              <Text style={styles.feeLabel}>Platform Fee</Text>
              <Text style={styles.feeValue}>₹{totals.platformFee}</Text>
            </View>
            {totals.discount > 0 && (
              <View style={styles.feeRow}>
                <Text style={[styles.feeLabel, { color: colors.primary }]}>
                  Discount
                </Text>
                <Text style={[styles.feeValue, { color: colors.primary }]}>
                  -₹{totals.discount}
                </Text>
              </View>
            )}
            <View style={[styles.feeRow, styles.totalRow]}>
              <Text style={styles.totalLabel}>Total</Text>
              <Text style={styles.totalValue}>₹{totals.total}</Text>
            </View>

            {totals.discount > 0 && (
              <View style={styles.savingsBanner}>
                <Text style={styles.savingsIcon}>🎉</Text>
                <Text style={styles.savingsText}>
                  You're saving ₹{totals.discount} on this order
                </Text>
              </View>
            )}
          </View>
        </View>
      </ScrollView>

      <View style={styles.bottomPanel}>
        <View style={styles.bottomTotalWrap}>
          <Text style={styles.bottomTotalLabel}>Total</Text>
          <Text style={styles.bottomTotal}>₹{totals.total}</Text>
        </View>
        <PrimaryButton
          title="Proceed to Checkout"
          onPress={() => navigation.navigate('CheckoutAddressScreen')}
          style={styles.checkoutButton}
        />
      </View>
    </View>
  );
};
