import React, { useEffect, useState, useContext, createContext } from 'react';
import {
  View, Text, FlatList, TouchableOpacity, StyleSheet,
  ActivityIndicator, Alert, TextInput,
} from 'react-native';
import { fetchProducts } from '../../services/api';
import { Product, CartItem } from '../../types';

// Simple cart context — lifted to App level in production
export const CartContext = createContext<{
  cart: CartItem[];
  addToCart: (product: Product) => void;
  clearCart: () => void;
}>({ cart: [], addToCart: () => {}, clearCart: () => {} });

export default function ProductListScreen({ navigation }: any) {
  const [products, setProducts] = useState<Product[]>([]);
  const [filtered, setFiltered] = useState<Product[]>([]);
  const [loading, setLoading]   = useState(true);
  const [search, setSearch]     = useState('');
  const [cart, setCart]         = useState<CartItem[]>([]);

  useEffect(() => {
    loadProducts();
  }, []);

  const loadProducts = async () => {
    setLoading(true);
    try {
      const data = await fetchProducts();
      setProducts(data);
      setFiltered(data);
    } catch {
      Alert.alert('Error', 'Could not load products.');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (text: string) => {
    setSearch(text);
    const lower = text.toLowerCase();
    setFiltered(products.filter(p =>
      p.name.toLowerCase().includes(lower) ||
      (p.description || '').toLowerCase().includes(lower)
    ));
  };

  const addToCart = (product: Product) => {
    setCart(prev => {
      const existing = prev.find(i => i.product.id === product.id);
      if (existing) return prev.map(i => i.product.id === product.id ? { ...i, quantity: i.quantity + 1 } : i);
      return [...prev, { product, quantity: 1 }];
    });
    Alert.alert('Added!', `${product.name} added to cart.`);
  };

  const renderItem = ({ item }: { item: Product }) => (
    <View style={styles.card}>
      <View style={styles.cardHeader}>
        <Text style={styles.category}>{item.category.toUpperCase()}</Text>
        <Text style={styles.stock}>Stock: {item.stock}</Text>
      </View>
      <Text style={styles.name}>{item.name}</Text>
      {item.description ? <Text style={styles.desc}>{item.description}</Text> : null}
      <View style={styles.cardFooter}>
        <Text style={styles.price}>₦{Number(item.price).toLocaleString()}</Text>
        <TouchableOpacity
          style={[styles.addBtn, item.stock === 0 && styles.disabled]}
          onPress={() => item.stock > 0 && addToCart(item)}
          disabled={item.stock === 0}
        >
          <Text style={styles.addBtnText}>{item.stock === 0 ? 'Out of Stock' : 'Add to Cart'}</Text>
        </TouchableOpacity>
      </View>
    </View>
  );

  return (
    <CartContext.Provider value={{ cart, addToCart, clearCart: () => setCart([]) }}>
      <View style={styles.bg}>
        <View style={styles.header}>
          <Text style={styles.title}>🛒 Products</Text>
          <TouchableOpacity onPress={() => navigation.navigate('Cart', { cart })} style={styles.cartBtn}>
            <Text style={styles.cartBtnText}>Cart ({cart.reduce((s, i) => s + i.quantity, 0)})</Text>
          </TouchableOpacity>
        </View>
        <TextInput
          style={styles.search}
          placeholder="Search products..."
          placeholderTextColor="#64748b"
          value={search}
          onChangeText={handleSearch}
        />
        {loading
          ? <ActivityIndicator color="#f97316" size="large" style={{ marginTop: 40 }} />
          : (
            <FlatList
              data={filtered}
              keyExtractor={i => i.id}
              renderItem={renderItem}
              contentContainerStyle={styles.list}
              ListEmptyComponent={<Text style={styles.empty}>No products found.</Text>}
            />
          )
        }
      </View>
    </CartContext.Provider>
  );
}

const styles = StyleSheet.create({
  bg:           { flex: 1, backgroundColor: '#0f172a' },
  header:       { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16 },
  title:        { fontSize: 20, fontWeight: '700', color: '#fff' },
  cartBtn:      { backgroundColor: '#f97316', borderRadius: 8, paddingHorizontal: 14, paddingVertical: 8 },
  cartBtnText:  { color: '#fff', fontWeight: '700' },
  search:       {
    backgroundColor: '#1e293b', margin: 16, marginTop: 0, borderRadius: 10,
    padding: 12, color: '#fff', fontSize: 14,
  },
  list:         { padding: 16, paddingTop: 0 },
  card:         { backgroundColor: '#1e293b', borderRadius: 14, padding: 16, marginBottom: 12 },
  cardHeader:   { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 },
  category:     { fontSize: 11, color: '#f97316', fontWeight: '700' },
  stock:        { fontSize: 11, color: '#64748b' },
  name:         { fontSize: 17, fontWeight: '700', color: '#fff', marginBottom: 4 },
  desc:         { fontSize: 13, color: '#94a3b8', marginBottom: 10 },
  cardFooter:   { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  price:        { fontSize: 18, fontWeight: '800', color: '#f97316' },
  addBtn:       { backgroundColor: '#f97316', borderRadius: 8, paddingHorizontal: 14, paddingVertical: 8 },
  disabled:     { backgroundColor: '#334155' },
  addBtnText:   { color: '#fff', fontWeight: '700', fontSize: 13 },
  empty:        { color: '#64748b', textAlign: 'center', marginTop: 40, fontSize: 15 },
});
