import React, { useEffect, useState } from 'react';
import { useRouter } from 'expo-router';
import { View, Text, Button, Alert, StyleSheet } from 'react-native';
import { getAuth } from 'firebase/auth';
import { collection, addDoc } from 'firebase/firestore'; // Make sure these are imported
import { db } from '@/firebase/config'; // Ensure this path is correct
import { useCart } from '@/app/context/cartContext';

const CartScreen = () => {
  const { cart, clearCart } = useCart();
  const auth = getAuth();
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const router = useRouter();

  // Check if the user is logged in when the component mounts
  useEffect(() => {
    const user = auth.currentUser;
    if (user) {
      setIsAuthenticated(true);
    } else {
      setIsAuthenticated(false);
      router.push('../screens/auth/SignInScreen'); // Redirect to sign-in screen if not logged in
    }
  }, [auth, router]);

  const handleConfirmOrder = async () => {
    if (!isAuthenticated) {
      Alert.alert('Erreur', 'Utilisateur non connecté.');
      return;
    }

    if (cart.total <= 0) {
      Alert.alert('Panier vide', 'Veuillez ajouter des produits à votre panier');
      return;
    }

    try {
      const userId = auth.currentUser?.uid;
      if (!userId) {
        Alert.alert('Erreur', 'Utilisateur non connecté.');
        return;
      }

      const orderData: any = {
        userId,
        status: 'En attente',
      };

      cart.items.forEach((item, index) => {
        orderData[`item${index + 1}`] = [item.quantity, item.productName];
      });

      await addDoc(collection(db, 'orders'), orderData);

      Alert.alert('Commande confirmée', 'Votre commande a été enregistrée.');
      clearCart();
    } catch (error) {
      console.error('Erreur de commande', error);
      Alert.alert('Erreur', "Impossible d'enregistrer la commande.");
    }
  };

  if (!isAuthenticated) {
    return <Text>Chargement...</Text>; // Loading state while checking authentication
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Votre Panier</Text>

      {cart.items.length === 0 ? (
        <Text style={styles.empty}>Votre panier est vide.</Text>
      ) : (
        cart.items.map((item, index) => (
          <View key={index} style={styles.itemContainer}>
            <Text style={styles.itemText}>
              {item.productName} - Quantité : {item.quantity}
            </Text>
          </View>
        ))
      )}

      {cart.items.length > 0 && (
        <View style={styles.buttonContainer}>
          <Button title="Confirmer la commande" onPress={handleConfirmOrder} color="#8B4513" />
          <View style={{ marginTop: 10 }}>
            <Button title="Vider le panier" onPress={clearCart} color="#A52A2A" />
          </View>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    backgroundColor: '#FFF',
    flexGrow: 1,
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
    marginBottom: 15,
    textAlign: 'center',
    color: '#5A3E36',
  },
  empty: {
    fontSize: 16,
    color: '#777',
    textAlign: 'center',
    marginTop: 50,
  },
  itemContainer: {
    backgroundColor: '#F5F5DC',
    padding: 15,
    marginBottom: 10,
    borderRadius: 10,
    borderColor: '#DDD',
    borderWidth: 1,
  },
  itemText: {
    fontSize: 16,
    color: '#333',
  },
  buttonContainer: {
    marginTop: 30,
  },
});

export default CartScreen;
