import React, { useCallback,useEffect, useState } from 'react';
import { View, Text, StyleSheet, Image,BackHandler,ActivityIndicator } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { useRouter } from 'expo-router';
import { BellRing } from 'lucide-react-native';
import COLORS from '@/constants/colors';
import { useFocusEffect } from '@react-navigation/native';
import { db } from '@/firebase/config'; // Firebase configuration
import { doc, getDoc } from 'firebase/firestore';
import { getAuth } from 'firebase/auth'; // Import Firebase Authentication



const UserHomeScreen = () => {
  const router = useRouter();
  const [coffeeShopName, setCoffeeShopName] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  // Fetch the current user's UID
  const currentUser = getAuth().currentUser; // Get the current user from Firebase Authentication

  // Fetch coffee shop name based on the current user's ownerId
  useEffect(() => {
    const fetchCoffeeShopName = async () => {
      if (currentUser) {
        try {
          const docRef = doc(db, 'coffee_shops', currentUser.uid); // Use the user's UID to fetch data
          const docSnap = await getDoc(docRef);
          if (docSnap.exists()) {
            const data = docSnap.data();
            setCoffeeShopName(data?.cafeName || "Nom de Café");
          } else {
            console.log("No such coffee shop!");
            setCoffeeShopName("Nom de Café");
          }
        } catch (error) {
          console.error("Error fetching coffee shop data:", error);
          setCoffeeShopName("Nom de Café");
        } finally {
          setLoading(false);
        }
      }
    };

    fetchCoffeeShopName();
  }, [currentUser]);

// Empêcher retour arrière
useFocusEffect(
  useCallback(() => {
    const onBackPress = () => true;
    BackHandler.addEventListener('hardwareBackPress', onBackPress);
    return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress);
  }, [])
);

  return (
    <View style={styles.container}>
        <View style={styles.header}>
          <View>
            <Text style={styles.welcome}>Bienvenue,</Text>
            {loading ? (
            <ActivityIndicator size="small" color={COLORS.primary} />
          ) : (
            <Text style={styles.shopName}>{coffeeShopName}</Text>
          )}
          </View>
          <View style={styles.notification}>
            <TouchableOpacity>
            <BellRing size={24} color="#000" />
            </TouchableOpacity>
          </View>
        </View>

        <Text style={styles.sectionTitle}>Nos Produits</Text>

        <View style={styles.categories}>
          <TouchableOpacity
            style={styles.categoryCard}
            onPress={() => router.push('/screens/user/GrainsScreen')}>

            <Image
              source={require('../../../assets/images/grains.jpg')} style={styles.categoryImage}
            />
            <Text style={styles.categoryTitle}>Grains de café</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.categoryCard}>
            <Image
                source={require('../../../assets/images/material.jpg')} style={styles.categoryImage}
            />
            <Text style={styles.categoryTitle}>Matériels</Text>
          </TouchableOpacity>
        </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F8F9FA',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    marginTop:26,
    borderBottomWidth:0.2,
    borderColor:'#999',
  },
  welcome: {
    fontSize: 16,
    color: '#666',
  },
  shopName: {
    fontSize: 20,
    fontWeight: '700',
    color: '#333',
  },
  notification:{
    backgroundColor:COLORS.secondary,
    padding:8,
    borderRadius:8,
    borderColor:'#000',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 5,
    },
    shadowOpacity: 0.2,
    shadowRadius: 10,
    elevation: 2,
  },
  
  sectionTitle: {
    fontSize: 26,
    fontWeight: '900',
    color: '#666',
   alignSelf:'center',
   marginTop:10,

  },
  categories: {
    flex: 1,
    padding: 15,
    justifyContent: 'space-evenly',
  },
  categoryCard: {
    backgroundColor: COLORS.secondary,
    borderRadius: 16,
    marginBottom: 16,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  categoryImage: {
    width: '80%',
    alignSelf: 'center',
    height: 160,
    marginTop: 15,
    borderRadius:16,
  },
  categoryTitle: {
    fontSize: 20,
    alignSelf:'center',
    fontWeight: '800',
    color: '#000',
    padding: 16,
  },
});

export default UserHomeScreen;


