import React from 'react';
import { View, Text, StyleSheet, ScrollView, Alert, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { useApp } from '../context/AppContext';
import { Button } from '../components/ui/Button';
import { currency } from '../lib/format';

export default function Cart() {
  const navigation = useNavigation();
  const { cart, shops, removeFromCart, placeOrder, user } = useApp();

  if (!cart.length) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.emptyState}>
          <Text style={styles.emptyIcon}>🛒</Text>
          <Text style={styles.emptyTitle}>Carrinho vazio</Text>
          <Text style={styles.emptyText}>Adicione serviços ou produtos para começar.</Text>
          <Button variant="outline" style={{ marginTop: 20 }} onPress={() => navigation.navigate('Explore' as never)}>
            Explorar Barbearias
          </Button>
        </View>
      </SafeAreaView>
    );
  }

  const grouped = cart.reduce<Record<string, typeof cart>>((acc, item) => {
    acc[item.shopId] = acc[item.shopId] || [];
    acc[item.shopId].push(item);
    return acc;
  }, {});

  const handleCheckout = async (shopId: string) => {
    if (!user) {
      Alert.alert('Sessão Necessária', 'Inicie sessão para confirmar o seu pedido');
      navigation.navigate('Login' as never);
      return;
    }
    const order = await placeOrder(user.id, shopId);
    if (order) {
      Alert.alert('Sucesso', 'Pedido criado com sucesso!');
    } else {
      Alert.alert('Erro', 'Não foi possível criar o pedido.');
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        <Text style={styles.title}>Carrinho</Text>

        {Object.entries(grouped).map(([shopId, items]) => {
          const shop = shops.find((s) => s.id === shopId);
          const total = items.reduce((sum, i) => {
            const price =
              i.type === 'service'
                ? shop?.services.find((s) => s.id === i.refId)?.price ?? 0
                : shop?.products.find((p) => p.id === i.refId)?.price ?? 0;
            return sum + price * i.qty;
          }, 0);

          return (
            <View key={shopId} style={styles.shopCard}>
              <View style={styles.shopHeader}>
                <View style={styles.shopIcon}>
                  <Text style={styles.shopIconText}>{(shop?.name || 'B').charAt(0)}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={styles.shopName}>{shop?.name ?? 'Barbearia'}</Text>
                  <Text style={styles.shopAddress}>{shop?.address}</Text>
                </View>
              </View>

              <View style={styles.divider} />

              {items.map((i) => {
                const ref =
                  i.type === 'service'
                    ? shop?.services.find((s) => s.id === i.refId)
                    : shop?.products.find((p) => p.id === i.refId);
                const price = ref?.price ?? 0;
                return (
                  <View key={i.refId} style={styles.item}>
                    <View style={styles.itemInfo}>
                      <View style={styles.typePill}>
                        <Text style={styles.typeText}>
                          {i.type === 'service' ? 'Serviço' : 'Produto'}
                        </Text>
                      </View>
                      <Text style={styles.itemName}>{ref?.name ?? 'Item'}</Text>
                      <Text style={styles.itemQty}>Qtd: {i.qty} · {currency(price * i.qty)}</Text>
                    </View>
                    <TouchableOpacity onPress={() => removeFromCart(i.refId)} style={styles.removeBtn}>
                      <Text style={styles.removeText}>✕</Text>
                    </TouchableOpacity>
                  </View>
                );
              })}

              <View style={styles.divider} />

              <View style={styles.totalRow}>
                <Text style={styles.totalLabel}>Total</Text>
                <Text style={styles.totalValue}>{currency(total)}</Text>
              </View>

              <Button
                onPress={() => (user ? handleCheckout(shopId) : navigation.navigate('Login' as never))}
                style={styles.checkoutBtn}
              >
                {user ? 'Finalizar Aquisição' : 'Entrar para Adquirir'}
              </Button>
            </View>
          );
        })}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0a0a0f',
  },
  content: {
    padding: 20,
    gap: 20,
    paddingBottom: 32,
  },
  title: {
    fontSize: 32,
    fontWeight: '900',
    color: '#f8fafc',
    marginBottom: 8,
  },
  emptyState: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 40,
    gap: 12,
  },
  emptyIcon: {
    fontSize: 56,
    marginBottom: 8,
  },
  emptyTitle: {
    color: '#f8fafc',
    fontSize: 22,
    fontWeight: '800',
  },
  emptyText: {
    color: '#64748b',
    fontSize: 15,
    textAlign: 'center',
  },
  shopCard: {
    backgroundColor: '#141420',
    borderRadius: 24,
    padding: 20,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.06)',
    marginBottom: 16,
  },
  shopHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 14,
  },
  shopIcon: {
    width: 48,
    height: 48,
    borderRadius: 16,
    backgroundColor: 'rgba(99,102,241,0.12)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  shopIconText: {
    color: '#818cf8',
    fontSize: 18,
    fontWeight: '900',
  },
  shopName: {
    fontSize: 18,
    fontWeight: '800',
    color: '#f8fafc',
  },
  shopAddress: {
    fontSize: 13,
    color: '#475569',
    marginTop: 2,
  },
  divider: {
    height: 1,
    backgroundColor: 'rgba(255,255,255,0.06)',
    marginVertical: 16,
  },
  item: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 12,
  },
  itemInfo: {
    flex: 1,
    gap: 4,
  },
  typePill: {
    alignSelf: 'flex-start',
    backgroundColor: 'rgba(99,102,241,0.1)',
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 3,
    marginBottom: 4,
  },
  typeText: {
    color: '#818cf8',
    fontSize: 10,
    fontWeight: '800',
    textTransform: 'uppercase',
  },
  itemName: {
    fontSize: 16,
    fontWeight: '700',
    color: '#f8fafc',
  },
  itemQty: {
    fontSize: 13,
    color: '#64748b',
    fontWeight: '500',
  },
  removeBtn: {
    width: 36,
    height: 36,
    borderRadius: 12,
    backgroundColor: 'rgba(239,68,68,0.08)',
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 12,
  },
  removeText: {
    color: '#ef4444',
    fontSize: 14,
    fontWeight: '800',
  },
  totalRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  totalLabel: {
    color: '#94a3b8',
    fontSize: 14,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 1,
  },
  totalValue: {
    color: '#a5b4fc',
    fontSize: 26,
    fontWeight: '900',
  },
  checkoutBtn: {
    backgroundColor: '#6366f1',
    borderRadius: 16,
    paddingVertical: 16,
  },
});
