import React, { useState } from 'react';
import {
  View, Text, FlatList, TouchableOpacity,
  StyleSheet, Alert, TextInput, ActivityIndicator, ScrollView,
} from 'react-native';
import { placeOrder } from '../../services/api';
import { CartItem } from '../../types';

export default function CartScreen({ route, navigation }: any) {
  const [cart, setCart]             = useState<CartItem[]>(route?.params?.cart || []);
  const [fulfillment, setFulfillment] = useState<'delivery' | 'pickup'>('delivery');
  const [address, setAddress]       = useState('');
  const [notes, setNotes]           = useState('');
  const [loading, setLoading]       = useState(false);

  const total = cart.reduce((s, i) => s + i.product.price * i.quantity, 0);

  const changeQty = (id: string, delta: number) => {
    setCart(prev =>
      prev
        .map(i => i.product.id === id ? { ...i, quantity: i.quantity + delta } : i)
        .filter(i => i.quantity > 0)
    );
  };

  const handlePlaceOrder = async () => {
    if (cart.length === 0) { Alert.alert('Empty Cart', 'Add items first.'); return; }
    if (fulfillment === 'delivery' && !address.trim()) {
      Alert.alert('Address Required', 'Please enter your delivery address.');
      return;
    }
    setLoading(true);
    try {
      await placeOrder({
        items: cart.map(i => ({
          productId: i.product.id,
          productName: i.product.name,
          category: i.product.category,
          quantity: i.quantity,
          price: i.product.price,
        })),
        fulfillment,
        address: address.trim() || undefined,
        notes: notes.trim() || undefined,
      });
      Alert.alert('Order Placed! 🎉', 'Your Cash on Delivery order has been placed. We will contact you shortly.', [
        { text: 'OK', onPress: () => { setCart([]); navigation.navigate('MyOrders'); } },
      ]);
    } catch (err: any) {
      Alert.alert('Error', err?.response?.data?.error || 'Failed to place order.');
    } finally {
      setLoading(false);
    }
  };

  if (cart.length === 0) {
    return (
      <View style={styles.empty}>
        <Text style={styles.emptyEmoji}>🛒</Text>
        <Text style={styles.emptyText}>Your cart is empty</Text>
        <TouchableOpacity style={styles.shopBtn} onPress={() => navigation.navigate('Products')}>
          <Text style={styles.shopBtnText}>Browse Products</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <ScrollView style={styles.bg} contentContainerStyle={styles.container}>
      <Text style={styles.title}>🛍️ Your Cart</Text>

      {cart.map(item => (
        <View key={item.product.id} style={styles.card}>
          <Text style={styles.itemName}>{item.product.name}</Text>
          <Text style={styles.itemPrice}>₦{Number(item.product.price).toLocaleString()} each</Text>
          <View style={styles.qtyRow}>
            <TouchableOpacity style={styles.qtyBtn} onPress={() => changeQty(item.product.id, -1)}>
              <Text style={styles.qtyBtnText}>−</Text>
            </TouchableOpacity>
            <Text style={styles.qty}>{item.quantity}</Text>
            <TouchableOpacity style={styles.qtyBtn} onPress={() => changeQty(item.product.id, 1)}>
              <Text style={styles.qtyBtnText}>+</Text>
            </TouchableOpacity>
            <Text style={styles.subtotal}>
              ₦{(item.product.price * item.quantity).toLocaleString()}
            </Text>
          </View>
        </View>
      ))}

      <View style={styles.totalCard}>
        <Text style={styles.totalLabel}>Total</Text>
        <Text style={styles.totalValue}>₦{total.toLocaleString()}</Text>
      </View>

      {/* Fulfillment */}
      <Text style={styles.sectionLabel}>Delivery Method</Text>
      <View style={styles.toggle}>
        <TouchableOpacity
          style={[styles.toggleBtn, fulfillment === 'delivery' && styles.toggleActive]}
          onPress={() => setFulfillment('delivery')}
        >
          <Text style={[styles.toggleText, fulfillment === 'delivery' && styles.toggleTextActive]}>🚚 Delivery</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.toggleBtn, fulfillment === 'pickup' && styles.toggleActive]}
          onPress={() => setFulfillment('pickup')}
        >
          <Text style={[styles.toggleText, fulfillment === 'pickup' && styles.toggleTextActive]}>🏪 Pickup</Text>
        </TouchableOpacity>
      </View>

      {fulfillment === 'delivery' && (
        <TextInput
          style={styles.input}
          placeholder="Delivery address *"
          placeholderTextColor="#64748b"
          value={address}
          onChangeText={setAddress}
          multiline
        />
      )}

      <TextInput
        style={styles.input}
        placeholder="Order notes (optional)"
        placeholderTextColor="#64748b"
        value={notes}
        onChangeText={setNotes}
        multiline
      />

      <View style={styles.codBadge}>
        <Text style={styles.codText}>💵 Payment: Cash on Delivery</Text>
      </View>

      <TouchableOpacity style={styles.placeBtn} onPress={handlePlaceOrder} disabled={loading}>
        {loading
          ? <ActivityIndicator color="#fff" />
          : <Text style={styles.placeBtnText}>Place Order</Text>}
      </TouchableOpacity>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  bg:              { flex: 1, backgroundColor: '#0f172a' },
  container:       { padding: 20 },
  title:           { fontSize: 22, fontWeight: '800', color: '#fff', marginBottom: 16 },
  card:            { backgroundColor: '#1e293b', borderRadius: 12, padding: 14, marginBottom: 10 },
  itemName:        { fontSize: 16, fontWeight: '700', color: '#fff' },
  itemPrice:       { fontSize: 13, color: '#94a3b8', marginBottom: 8 },
  qtyRow:          { flexDirection: 'row', alignItems: 'center', gap: 12 },
  qtyBtn:          { backgroundColor: '#334155', borderRadius: 8, width: 32, height: 32, alignItems: 'center', justifyContent: 'center' },
  qtyBtnText:      { color: '#fff', fontSize: 18, fontWeight: '700' },
  qty:             { color: '#fff', fontSize: 16, fontWeight: '700', minWidth: 24, textAlign: 'center' },
  subtotal:        { color: '#f97316', fontWeight: '700', marginLeft: 'auto' },
  totalCard:       { backgroundColor: '#1e293b', borderRadius: 12, padding: 16, flexDirection: 'row', justifyContent: 'space-between', marginVertical: 16 },
  totalLabel:      { color: '#94a3b8', fontSize: 16 },
  totalValue:      { color: '#f97316', fontSize: 20, fontWeight: '800' },
  sectionLabel:    { color: '#fff', fontSize: 15, fontWeight: '700', marginBottom: 8 },
  toggle:          { flexDirection: 'row', gap: 10, marginBottom: 14 },
  toggleBtn:       { flex: 1, backgroundColor: '#1e293b', borderRadius: 10, padding: 12, alignItems: 'center', borderWidth: 1, borderColor: '#334155' },
  toggleActive:    { borderColor: '#f97316', backgroundColor: 'rgba(249,115,22,0.1)' },
  toggleText:      { color: '#94a3b8', fontWeight: '600' },
  toggleTextActive:{ color: '#f97316' },
  input:           { backgroundColor: '#1e293b', borderRadius: 10, padding: 14, color: '#fff', marginBottom: 12, fontSize: 14, borderWidth: 1, borderColor: '#334155' },
  codBadge:        { backgroundColor: 'rgba(34,197,94,0.1)', borderRadius: 10, padding: 12, marginBottom: 16, borderWidth: 1, borderColor: '#22c55e' },
  codText:         { color: '#22c55e', fontWeight: '700', textAlign: 'center' },
  placeBtn:        { backgroundColor: '#f97316', borderRadius: 12, padding: 18, alignItems: 'center' },
  placeBtnText:    { color: '#fff', fontSize: 16, fontWeight: '800' },
  empty:           { flex: 1, backgroundColor: '#0f172a', alignItems: 'center', justifyContent: 'center' },
  emptyEmoji:      { fontSize: 60, marginBottom: 12 },
  emptyText:       { color: '#94a3b8', fontSize: 18, marginBottom: 20 },
  shopBtn:         { backgroundColor: '#f97316', borderRadius: 10, paddingHorizontal: 24, paddingVertical: 12 },
  shopBtnText:     { color: '#fff', fontWeight: '700', fontSize: 15 },
});
