import { Link } from 'expo-router';
import { SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { CustomerBottomNav } from '../components/customer-bottom-nav';
import { CustomerPageHeader } from '../components/customer-page-header';
import { formatCurrency, useCustomerOrder } from '../src/store/order';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

export default function CustomerCartScreen() {
  const { cart, storefront, updateQuantity, removeItem, couponCode } = useCustomerOrder();
  const { mode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);
  const subtotal = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const estimatedDelivery = Number(storefront?.baseDeliveryFee ?? 0);
  const estimatedTotal = subtotal + estimatedDelivery;

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content}>
          <CustomerPageHeader title="Seu carrinho" subtitle="Revise os itens antes de fechar o pedido." backHref="/search" backLabel="Continuar pedindo" />

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            {!cart.length ? <Text style={[styles.row, { color: theme.textMuted }]}>Seu carrinho ainda esta vazio.</Text> : null}
            {cart.map((item) => (
              <View key={item.productId} style={[styles.itemRow, { borderTopColor: theme.cardBorder }]}>
                <View style={styles.itemInfo}>
                  <Text style={[styles.itemTitle, { color: theme.text }]}>{item.name}</Text>
                  <Text style={[styles.row, { color: theme.textMuted }]}>{formatCurrency(item.price)} por unidade</Text>
                  {item.notes ? <Text style={[styles.row, { color: theme.textMuted }]}>{item.notes}</Text> : null}
                </View>
                <View style={styles.itemActions}>
                  <TouchableOpacity onPress={() => updateQuantity(item.productId, item.quantity - 1)} style={styles.quantityButton}>
                    <Text style={styles.quantityButtonText}>-</Text>
                  </TouchableOpacity>
                  <Text style={[styles.quantityValue, { color: theme.text }]}>{item.quantity}</Text>
                  <TouchableOpacity onPress={() => updateQuantity(item.productId, item.quantity + 1)} style={styles.quantityButton}>
                    <Text style={styles.quantityButtonText}>+</Text>
                  </TouchableOpacity>
                  <TouchableOpacity onPress={() => removeItem(item.productId)} style={styles.removeButton}>
                    <Text style={styles.removeButtonText}>Remover</Text>
                  </TouchableOpacity>
                </View>
              </View>
            ))}
          </View>

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Resumo</Text>
            <Text style={[styles.row, { color: theme.textMuted }]}>Subtotal {formatCurrency(subtotal)}</Text>
            <Text style={[styles.row, { color: theme.textMuted }]}>Entrega estimada {formatCurrency(estimatedDelivery)}</Text>
            {couponCode ? <Text style={[styles.row, { color: theme.textSoft }]}>Cupom selecionado {couponCode}</Text> : null}
            <Text style={[styles.total, { color: theme.accent }]}>Total estimado {formatCurrency(estimatedTotal)}</Text>
          </View>

          <Link href="/checkout" style={[styles.primaryButton, { backgroundColor: theme.accent, color: theme.accentText }]}>Ir para checkout</Link>
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { padding: 16, gap: 12, paddingBottom: 22 },
  card: { borderRadius: 18, padding: 15, borderWidth: 1 },
  sectionTitle: { fontSize: 17, fontWeight: '800' },
  row: { marginTop: 8, fontSize: 13 },
  itemRow: { marginTop: 12, borderTopWidth: 1, borderTopColor: '#1E293B', paddingTop: 12 },
  itemInfo: { gap: 4 },
  itemTitle: { fontSize: 15, fontWeight: '800' },
  itemActions: { marginTop: 10, flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 8 },
  quantityButton: { width: 32, height: 32, borderRadius: 16, backgroundColor: '#E2E8F0', alignItems: 'center', justifyContent: 'center' },
  quantityButtonText: { color: '#0F172A', fontSize: 16, fontWeight: '900' },
  quantityValue: { minWidth: 20, textAlign: 'center', fontWeight: '800' },
  removeButton: { borderRadius: 999, backgroundColor: '#fff1e8', paddingHorizontal: 12, paddingVertical: 8, borderWidth: 1, borderColor: '#fdba74' },
  removeButtonText: { color: '#9A3412', fontWeight: '900', fontSize: 11 },
  total: { marginTop: 12, fontSize: 17, fontWeight: '800' },
  primaryButton: { borderRadius: 999, textAlign: 'center', paddingHorizontal: 16, paddingVertical: 14, fontWeight: '900', overflow: 'hidden', marginBottom: 10, shadowColor: '#000000', shadowOpacity: 0.18, shadowRadius: 16, shadowOffset: { width: 0, height: 8 }, elevation: 6 },
});
