I want the searchbar and the barcode to be on the same level as the user.name in the profile screen
// screens/NutritionScreen.js

import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  Modal,
  TextInput,
  Alert,
  SafeAreaView,
} from 'react-native';
import { useTheme, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; // Ensure this is installed

const NutritionScreen = () => {
  const theme = useTheme(); // Access the current theme

  // State to manage food items
  const [foodItems, setFoodItems] = useState([
    {
      id: '1',
      name: 'Apple',
      calories: 95,
      protein: 0.5,
      carbs: 25,
      fat: 0.3,
      icon: 'food-apple',
    },
    {
      id: '2',
      name: 'Banana',
      calories: 105,
      protein: 1.3,
      carbs: 27,
      fat: 0.4,
      icon: 'food-croissant',
    },
    {
      id: '3',
      name: 'Grilled Chicken Breast',
      calories: 165,
      protein: 31,
      carbs: 0,
      fat: 3.6,
      icon: 'food-steak',
    },
    // Add more initial food items as needed
  ]);

  // State for modal visibility and new food entry
  const [modalVisible, setModalVisible] = useState(false);
  const [newFood, setNewFood] = useState({
    name: '',
    calories: '',
    protein: '',
    carbs: '',
    fat: '',
    icon: 'food',
  });

  // State for selected items
  const [selectedIds, setSelectedIds] = useState([]);

  // State for search query
  const [searchQuery, setSearchQuery] = useState('');

  // Calculate total nutrients based on filtered items
  const filteredFoodItems = foodItems.filter((item) =>
    item.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const totals = filteredFoodItems.reduce(
    (acc, item) => {
      acc.calories += parseFloat(item.calories) || 0;
      acc.protein += parseFloat(item.protein) || 0;
      acc.carbs += parseFloat(item.carbs) || 0;
      acc.fat += parseFloat(item.fat) || 0;
      return acc;
    },
    { calories: 0, protein: 0, carbs: 0, fat: 0 }
  );

  // Handle adding new food item
  const addFoodItem = () => {
    if (
      !newFood.name ||
      !newFood.calories ||
      !newFood.protein ||
      !newFood.carbs ||
      !newFood.fat
    ) {
      Alert.alert('Error', 'Please fill in all fields.');
      return;
    }

    const newItem = {
      id: (foodItems.length + 1).toString(),
      name: newFood.name,
      calories: parseFloat(newFood.calories),
      protein: parseFloat(newFood.protein),
      carbs: parseFloat(newFood.carbs),
      fat: parseFloat(newFood.fat),
      icon: newFood.icon,
    };

    setFoodItems([...foodItems, newItem]);
    setNewFood({
      name: '',
      calories: '',
      protein: '',
      carbs: '',
      fat: '',
      icon: 'food',
    });
    setModalVisible(false);
    clearSelection(); // Clear selections after adding a new item
  };

  // Handle deleting a single food item
  const deleteFoodItem = (id) => {
    Alert.alert(
      'Remove Food Item',
      'Are you sure you want to remove this food item?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Delete',
          style: 'destructive',
          onPress: () => {
            setFoodItems(foodItems.filter((item) => item.id !== id));
            // Also remove from selectedIds if it's selected
            setSelectedIds(selectedIds.filter((itemId) => itemId !== id));
          },
        },
      ]
    );
  };

  // Handle deleting multiple selected items
  const deleteSelectedItems = () => {
    Alert.alert(
      'Remove Selected Items',
      'Are you sure you want to remove the selected food items?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Delete',
          style: 'destructive',
          onPress: () => {
            setFoodItems(foodItems.filter((item) => !selectedIds.includes(item.id)));
            clearSelection();
          },
        },
      ]
    );
  };

  // Toggle selection of an item
  const toggleSelection = (id) => {
    if (selectedIds.includes(id)) {
      setSelectedIds(selectedIds.filter((itemId) => itemId !== id));
    } else {
      setSelectedIds([...selectedIds, id]);
    }
  };

  // Clear all selections
  const clearSelection = () => {
    setSelectedIds([]);
  };

  // Handle barcode scanning (Stub Function)
  const handleBarcodeScan = () => {
    // Implement barcode scanning functionality here
    Alert.alert('Barcode Scan', 'Barcode scanning functionality to be implemented.');
  };

  // Render each food item
  const renderItem = ({ item }) => {
    const isSelected = selectedIds.includes(item.id);

    return (
      <TouchableOpacity
        onLongPress={() => toggleSelection(item.id)}
        onPress={() => {
          if (selectedIds.length > 0) {
            toggleSelection(item.id);
          }
        }}
        style={[
          styles.itemContainer,
          { borderColor: theme.colors.border, backgroundColor: theme.colors.surface },
          isSelected && styles.selectedItem,
        ]}
        activeOpacity={0.7}
        accessibilityLabel={`${isSelected ? 'Deselect' : 'Select'} ${item.name}`}
        accessibilityRole="button"
      >
        <Icon name={item.icon} size={30} color={theme.colors.primary} />
        <View style={styles.foodInfo}>
          <Text style={[styles.foodName, { color: theme.colors.text }]}>
            {item.name}
          </Text>
          <Text style={[styles.nutrients, { color: theme.colors.text }]}>
            Calories: {item.calories} kcal | Protein: {item.protein}g | Carbs: {item.carbs}g | Fat: {item.fat}g
          </Text>
        </View>
        <DeleteButton onPress={() => deleteFoodItem(item.id)} />
      </TouchableOpacity>
    );
  };

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.colors.background }]}>
      <View style={[styles.container, { backgroundColor: theme.colors.background }]}>
        {/* Search Bar */}
        <View style={styles.searchContainer}>
          <TextInput
            style={[
              styles.searchInput,
              {
                borderColor: theme.colors.border,
                backgroundColor: theme.colors.surface,
                color: theme.colors.text,
              },
            ]}
            placeholder="Search food items..."
            placeholderTextColor={theme.colors.placeholder}
            value={searchQuery}
            onChangeText={(text) => setSearchQuery(text)}
            returnKeyType="search"
            accessibilityLabel="Search food items"
          />
          <TouchableOpacity
            style={styles.barcodeButton}
            onPress={handleBarcodeScan}
            accessibilityLabel="Scan barcode"
            accessibilityRole="button"
          >
            <Icon name="barcode-scan" size={24} color={theme.colors.primary} />
          </TouchableOpacity>
        </View>

        {/* Total Nutrients Summary */}
        <View
          style={[
            styles.summaryContainer,
            { borderColor: theme.colors.border, backgroundColor: theme.colors.surface },
          ]}
        >
          <Text style={[styles.summaryText, { color: theme.colors.text }]}>
            Total Calories: {totals.calories} kcal
          </Text>
          <Text style={[styles.summaryText, { color: theme.colors.text }]}>
            Protein: {totals.protein}g | Carbs: {totals.carbs}g | Fat: {totals.fat}g
          </Text>
        </View>

        {/* Food Items List */}
        <FlatList
          data={filteredFoodItems}
          keyExtractor={(item) => item.id}
          renderItem={renderItem}
          contentContainerStyle={styles.list}
          ItemSeparatorComponent={() => <View style={{ height: 10 }} />}
        />

        {/* Add Food Button */}
        <TouchableOpacity
          style={[styles.addButton, { backgroundColor: theme.colors.primary }]}
          onPress={() => setModalVisible(true)}
          accessibilityLabel="Add a new food item"
          accessibilityRole="button"
        >
          <Icon name="plus" size={20} color="#fff" />
          <Text style={styles.addButtonText}>Add Food</Text>
        </TouchableOpacity>

        {/* Floating Delete Button for Selected Items */}
        {selectedIds.length > 0 && (
          <TouchableOpacity
            style={styles.floatingDeleteButton}
            onPress={deleteSelectedItems}
            accessibilityLabel="Delete selected food items"
            accessibilityRole="button"
          >
            <Text style={styles.floatingDeleteButtonText}>Delete Selected</Text>
          </TouchableOpacity>
        )}

        {/* Add Food Modal */}
        <Modal
          visible={modalVisible}
          animationType="slide"
          transparent={true}
          onRequestClose={() => setModalVisible(false)}
        >
          <View style={styles.modalOverlay}>
            <View
              style={[
                styles.modalContainer,
                { backgroundColor: theme.colors.background },
              ]}
            >
              <Text style={[styles.modalTitle, { color: theme.colors.text }]}>
                Add New Food
              </Text>
              <TextInput
                style={[
                  styles.input,
                  {
                    borderColor: theme.colors.border,
                    color: theme.colors.text,
                  },
                ]}
                placeholder="Food Name"
                placeholderTextColor={theme.colors.placeholder}
                value={newFood.name}
                onChangeText={(text) => setNewFood({ ...newFood, name: text })}
              />
              <TextInput
                style={[
                  styles.input,
                  {
                    borderColor: theme.colors.border,
                    color: theme.colors.text,
                  },
                ]}
                placeholder="Calories"
                placeholderTextColor={theme.colors.placeholder}
                keyboardType="numeric"
                value={newFood.calories}
                onChangeText={(text) => setNewFood({ ...newFood, calories: text })}
              />
              <TextInput
                style={[
                  styles.input,
                  {
                    borderColor: theme.colors.border,
                    color: theme.colors.text,
                  },
                ]}
                placeholder="Protein (g)"
                placeholderTextColor={theme.colors.placeholder}
                keyboardType="numeric"
                value={newFood.protein}
                onChangeText={(text) => setNewFood({ ...newFood, protein: text })}
              />
              <TextInput
                style={[
                  styles.input,
                  {
                    borderColor: theme.colors.border,
                    color: theme.colors.text,
                  },
                ]}
                placeholder="Carbs (g)"
                placeholderTextColor={theme.colors.placeholder}
                keyboardType="numeric"
                value={newFood.carbs}
                onChangeText={(text) => setNewFood({ ...newFood, carbs: text })}
              />
              <TextInput
                style={[
                  styles.input,
                  {
                    borderColor: theme.colors.border,
                    color: theme.colors.text,
                  },
                ]}
                placeholder="Fat (g)"
                placeholderTextColor={theme.colors.placeholder}
                keyboardType="numeric"
                value={newFood.fat}
                onChangeText={(text) => setNewFood({ ...newFood, fat: text })}
              />
              {/* Icon selection can be enhanced with a picker */}
              <TextInput
                style={[
                  styles.input,
                  {
                    borderColor: theme.colors.border,
                    color: theme.colors.text,
                  },
                ]}
                placeholder="Icon Name (e.g., food-apple)"
                placeholderTextColor={theme.colors.placeholder}
                value={newFood.icon}
                onChangeText={(text) => setNewFood({ ...newFood, icon: text })}
              />
              <View style={styles.modalButtons}>
                <Button mode="contained" onPress={addFoodItem}>
                  Add
                </Button>
                <Button
                  mode="outlined"
                  onPress={() => setModalVisible(false)}
                  style={{ marginLeft: 10 }}
                >
                  Cancel
                </Button>
              </View>
            </View>
          </View>
        </Modal>
      </View>
    </SafeAreaView>
  );
};

// Delete Button Component
const DeleteButton = ({ onPress }) => (
  <TouchableOpacity
    onPress={onPress}
    style={styles.deleteButton}
    accessibilityLabel="Delete food item"
    accessibilityRole="button"
  >
    <View style={styles.deleteIcon}>
      <View style={styles.horizontalLine} />
    </View>
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
  },
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 10, // Added top padding
    paddingBottom: 20,
    // backgroundColor handled by theming
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  searchInput: {
    flex: 1,
    height: 40,
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 10,
    fontSize: 16,
  },
  barcodeButton: {
    marginLeft: 10,
    padding: 8,
    borderRadius: 8,
    backgroundColor: '#F0F0F0', // Light gray background for contrast
    justifyContent: 'center',
    alignItems: 'center',
  },
  summaryContainer: {
    padding: 15,
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 15,
    // borderColor and backgroundColor handled dynamically
  },
  summaryText: {
    fontSize: 16,
    fontWeight: '600',
  },
  list: {
    paddingBottom: 20,
  },
  itemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    borderWidth: 1,
    borderRadius: 8,
    // borderColor and backgroundColor handled dynamically
  },
  selectedItem: {
    backgroundColor: '#D1F2EB', // Light teal background for selection
  },
  foodInfo: {
    marginLeft: 15,
    flex: 1,
  },
  foodName: {
    fontSize: 18,
    fontWeight: 'bold',
    // color handled dynamically
  },
  nutrients: {
    marginTop: 5,
    fontSize: 14,
    // color handled dynamically
  },
  addButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 15,
    borderRadius: 8,
    position: 'absolute',
    bottom: 20,
    left: 20,
    right: 20,
    // backgroundColor handled dynamically
  },
  addButtonText: {
    color: '#fff',
    marginLeft: 10,
    fontSize: 16,
    fontWeight: '600',
  },
  floatingDeleteButton: {
    position: 'absolute',
    bottom: 90,
    right: 20,
    backgroundColor: '#E74C3C',
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 25,
    elevation: 5,
  },
  floatingDeleteButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContainer: {
    width: '90%',
    padding: 20,
    borderRadius: 8,
    // backgroundColor handled dynamically
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 15,
    textAlign: 'center',
  },
  input: {
    borderWidth: 1,
    borderRadius: 6,
    padding: 10,
    marginBottom: 10,
    fontSize: 16,
    // borderColor and color handled dynamically
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10,
  },
  deleteButton: {
    marginLeft: 10,
    width: 30,
    height: 30,
    borderRadius: 15,
    backgroundColor: '#E74C3C', // Red background
    justifyContent: 'center',
    alignItems: 'center',
  },
  deleteIcon: {
    width: 16,
    height: 2,
    backgroundColor: '#fff',
  },
  horizontalLine: {
    width: '100%',
    height: 2,
    backgroundColor: '#fff',
  },
});

export default NutritionScreen;

// screens/ProfileScreen.js

import React, { useContext } from 'react';
import { View, StyleSheet, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { Title, Caption, Text, Button } from 'react-native-paper';
import { AuthContext } from '../context/AuthContext';
import { useTheme } from 'react-native-paper';

/**
 * ProfileScreen Component
 * Displays the authenticated user's profile information.
 */
const ProfileScreen = ({ navigation }) => {
  const { user, signOut, loading } = useContext(AuthContext);
  const theme = useTheme(); // Access the current theme

  /**
   * Handler for the logout button
   */
  const handleLogout = () => {
    Alert.alert(
      'Logout',
      'Are you sure you want to logout?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Logout',
          style: 'destructive',
          onPress: () => signOut(),
        },
      ],
      { cancelable: true }
    );
  };

  /**
   * If the app is still loading user data, show a loading indicator
   */
  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={theme.colors.primary} />
      </View>
    );
  }

  /**
   * If no user is logged in, prompt the user to log in
   */
  if (!user) {
    return (
      <View style={styles.container}>
        <Text>No user data available. Please log in.</Text>
        <Button
          mode="contained"
          onPress={() => navigation.navigate('Login')}
          style={styles.loginButton}
          accessibilityLabel="Navigate to Login"
        >
          Go to Login
        </Button>
      </View>
    );
  }

  /**
   * Render the user's profile information
   */
  return (
    <ScrollView
      contentContainerStyle={[styles.container, { backgroundColor: theme.colors.background }]}
    >
      {/* User Information Section */}
      <View style={styles.userInfoSection}>
        {user.name ? (
          <Title style={[styles.title, { color: theme.colors.text }]}>{user.name}</Title>
        ) : (
          <Title style={[styles.title, { color: theme.colors.text }]}>User ID: {user.id}</Title>
        )}
        {user.email && (
          <Caption style={[styles.caption, { color: theme.colors.text }]}>{user.email}</Caption>
        )}
      </View>

      {/* Logout Button */}
      <View style={styles.logoutSection}>
        <Button
          mode="contained"
          icon="logout"
          onPress={handleLogout}
          style={styles.logoutButton}
          contentStyle={styles.buttonContent}
          accessibilityLabel="Logout"
          accessibilityHint="Logs you out of the application"
        >
          Logout
        </Button>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
    padding: 20,
  },
  userInfoSection: {
    paddingHorizontal: 20,
    paddingVertical: 40,
    alignItems: 'center',
    backgroundColor: 'transparent',
  },
  title: {
    fontSize: 26,
    fontWeight: 'bold',
  },
  caption: {
    fontSize: 16,
    lineHeight: 16,
    marginTop: 5,
  },
  logoutSection: {
    paddingHorizontal: 20,
    marginTop: 30,
    alignItems: 'center',
  },
  logoutButton: {
    width: '100%',
    borderRadius: 5,
  },
  buttonContent: {
    height: 50,
    justifyContent: 'center',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loginButton: {
    marginTop: 20,
    borderRadius: 25,
    paddingHorizontal: 20,
    paddingVertical: 10,
  },
});

export default ProfileScreen;