import React, { useState, useEffect } from 'react';
import { FlatList, StyleSheet, View, Text, Alert, RefreshControl } from 'react-native';
import Animated, { FadeInUp } from 'react-native-reanimated';
import OrderItem from '@/components/OrderItem';
import { getAuth } from 'firebase/auth';
import { collection, query, where, getDocs } from 'firebase/firestore';
import { db } from '@/firebase/config';
import { Order } from '@/constants/types'; 
import COLORS from '@/constants/colors';

interface OrderListProps {
  // Accept a trigger or prop to refresh data
}

export default function OrderList() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const fetchOrders = async () => {
    const user = getAuth().currentUser;
    if (!user) {
      Alert.alert('Erreur', 'Utilisateur non connecté');
      return;
    }

    try {
      const ordersQuery = query(
        collection(db, 'orders'),
        where('userId', '==', user.uid)
      );

      const querySnapshot = await getDocs(ordersQuery);

      const ordersData = querySnapshot.docs.map((doc) => {
        const data = doc.data();
        const order: Order = {
          id: doc.id,
          orderId: data.orderId || '',
          items: Object.keys(data)
            .filter(key => key.startsWith('item'))
            .map((key) => ({
              name: data[key].name,
              quantity: data[key].quantity,
            })),
          status: data.status || '',
          timeAgo: data.createdAt ? new Date(data.createdAt).toLocaleString() : '',
          userId: data.userId || '',
          createdAt: data.createdAt ? new Date(data.createdAt.seconds * 1000) : new Date(), // Ensure it is a Date object
        };
        return order;
      });

      // Sort by orderId in descending order
      const sortedOrders = ordersData.sort((a, b) =>
        b.orderId.localeCompare(a.orderId) // reverse of localeCompare
      );

      setOrders(sortedOrders);
    } catch (error) {
      console.error('Erreur lors de la récupération des commandes:', error);
      Alert.alert('Erreur', "Impossible de récupérer les commandes.");
    } finally {
      setRefreshing(false); // stop the refreshing indicator after fetch
    }
  };

  const onRefresh = () => {
    setRefreshing(true);
    fetchOrders();
  };

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

  return (
    <FlatList
      data={orders}
      keyExtractor={(item) => item.id}
      renderItem={({ item, index }) => (
        <Animated.View
          entering={FadeInUp.delay(index * 100).springify()}
          style={styles.itemContainer}
        >
          <OrderItem order={item} />
        </Animated.View>
      )}
      contentContainerStyle={styles.listContent}
      showsVerticalScrollIndicator={false}
      ListEmptyComponent={
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>Aucune commande trouvée</Text>
        </View>
      }
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }
    />
  );
}

const styles = StyleSheet.create({
  listContent: {
    paddingTop: 16,
    paddingBottom: 24,
  },
  itemContainer: {
    marginBottom: 12,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 10,
  },
  emptyText: {
    color: COLORS.text,
    fontSize: 18,
  },
});
