import React, { useState, useEffect } from "react";
import { View, StyleSheet, Text, Modal, TextInput, ScrollView, Dimensions, Pressable, TouchableOpacity } from "react-native";
import ScheduleEditor from "./scheduleEditor";
import Animated, {
  SlideInDown,
  SlideOutDown,
  FadeIn,
  FadeOut,
} from 'react-native-reanimated';
import moment from "moment";
import Timetable from "react-native-calendar-timetable";
import Rectangle from "../common/rectanglev2";
import ButtonComp from "../common/Button";

const CALENDAR_WIDTH = 807;
const CALENDAR_HEIGHT = 670;

const AnimatedPressable = Animated.createAnimatedComponent(Pressable);


const EditSchedule = () => {
    // Set up the date range for Monday to Friday of the current week
    const [from] = React.useState(moment().startOf('week').add(1, 'days').toDate());
    const [till] = React.useState(moment().startOf('week').add(5, 'days').toDate());
    const [isOpen, setOpen] = useState(false);
    const [isAddingSchedule, setIsAddingSchedule] = useState(false);
    const [scheduleName, setScheduleName] = useState('');
    const [tempSchedules, setTempSchedules] = useState([]);
    const [currentSchedule, setCurrentSchedule] = useState( {
        id: 0,
        name: "Default Schedule",
        items: [
        {
          title: 'Monday',
          startDate: moment().startOf('week').add(1, 'days').hour(8).toDate(),
          endDate: moment().startOf('week').add(1, 'days').hour(10).toDate(),
        },
        {
          title: 'Tuesday',
          startDate: moment().startOf('week').add(2, 'days').hour(8).toDate(),
          endDate: moment().startOf('week').add(2, 'days').hour(10).toDate(),
        },
        {
          title: 'Wednesday',
          startDate: moment().startOf('week').add(3, 'days').hour(8).toDate(),
          endDate: moment().startOf('week').add(3, 'days').hour(10).toDate(),
        },
        {
          title: 'Thursday',
          startDate: moment().startOf('week').add(4, 'days').hour(8).toDate(),
          endDate: moment().startOf('week').add(4, 'days').hour(10).toDate(),
        },
        {
          title: 'Friday',
          startDate: moment().startOf('week').add(5, 'days').hour(8).toDate(),
          endDate: moment().startOf('week').add(5, 'days').hour(10).toDate(),
        },
      ]
    });

    const range = { from, till };
    // Set up the event data
    // the data below will eventually be fetched from the database
    const [allSchedules, setAllSchedules] = React.useState([
        {
            id: 0,
            name: "Default Schedule",
            items: [
            {
              title: 'Monday',
              startDate: moment().startOf('week').add(1, 'days').hour(8).toDate(),
              endDate: moment().startOf('week').add(1, 'days').hour(10).toDate(),
            },
            {
              title: 'Tuesday',
              startDate: moment().startOf('week').add(2, 'days').hour(8).toDate(),
              endDate: moment().startOf('week').add(2, 'days').hour(10).toDate(),
            },
            {
              title: 'Wednesday',
              startDate: moment().startOf('week').add(3, 'days').hour(8).toDate(),
              endDate: moment().startOf('week').add(3, 'days').hour(10).toDate(),
            },
            {
              title: 'Thursday',
              startDate: moment().startOf('week').add(4, 'days').hour(8).toDate(),
              endDate: moment().startOf('week').add(4, 'days').hour(10).toDate(),
            },
            {
              title: 'Friday',
              startDate: moment().startOf('week').add(5, 'days').hour(8).toDate(),
              endDate: moment().startOf('week').add(5, 'days').hour(10).toDate(),
            },
          ]
        },
        // You can add more schedules here
      ]);

    // Combine allSchedules and tempSchedules
    const combinedSchedules = [...allSchedules, ...tempSchedules];

    const handleScheduleCreation = (selectedDays, startHour, startMinute, endHour, endMinute) => {
        const daysIndex = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
        console.log(selectedDays, 'selectedDays');
        const newItems = selectedDays.map((day) => {
            return {
                title: day,
                startDate: moment().startOf('week').add(daysIndex.indexOf(day) + 1, 'days').hour(startHour).minute(startMinute).toDate(),
                endDate: moment().startOf('week').add(daysIndex.indexOf(day) + 1, 'days').hour(endHour).minute(endMinute).toDate()
            };
        });

        setCurrentSchedule({
            ...currentSchedule,
            items: newItems
        });
        // add the new schedule into last element of tempSchedules
        setTempSchedules( prevArray => [
            ...prevArray.slice(0, -1),
            {
                ...prevArray[prevArray.length - 1],
                items: newItems
            }
        ]);
    };

    // ... existing code ...

useEffect(() => {
        console.log('Current Schedule updateds:', currentSchedule);
    }, [currentSchedule]);

    useEffect(() => {
        console.log('Temp Schedules updated:', tempSchedules);
    }, [tempSchedules]);

// ... rest of the component ...

    const CustomHeader = ({ date }) => (
        <View style={styles.headerContainer}>
            <Text style={styles.headerText}>{moment(date).format('ddd')}</Text>
        </View>
    );

    const calculateDayIndex = (date) => {
        return moment(date).isoWeekday();
    };

    const addNewSchedule = () => {
        if (scheduleName.trim()) {
            setTempSchedules([...tempSchedules, {
                id: allSchedules.length,
                name: scheduleName,
                // items will be initialized as an empty array because the user will be adding events later
                items: []
            }]);
            setCurrentSchedule([]);
            setScheduleName('');
            setIsAddingSchedule(false);
        }
    };

    const handleSave = () => {
        const scheduleToSave = tempSchedules.find(schedule => schedule.id === currentSchedule.id);
        if(scheduleToSave){
            const updatedSchedules = allSchedules.map((schedule) => {
                return schedule.id === scheduleToSave.id
                ? {
                    ...schedule,
                    items: currentSchedule.items
                }
                : schedule;
            });
            setAllSchedules(updatedSchedules);
            console.log('schedules updated', updatedSchedules);
        } else {
            console.log('schedule not found');
        }
    };

    const handleScheduleViewChange = (scheduleName) => {
        const selectedSchedule = combinedSchedules.find(schedule => schedule.name === scheduleName);
        if (selectedSchedule) {
            setCurrentSchedule(selectedSchedule);
        }
    };

    return (
        <View style={styles.container}>
            <View style={styles.contentContainer}>
                <View style={styles.schedulesContainer}>
                    <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                        {combinedSchedules.map((schedule, index) => (
                            <TouchableOpacity 
                                key={index} 
                                style={currentSchedule.name === schedule.name ? styles.activeSchedule : styles.schedule} 
                                onPress={() => handleScheduleViewChange(schedule.name)}
                            >
                                <Text style={currentSchedule.name === schedule.name ? styles.activeScheduleText : styles.scheduleText}>
                                    {schedule.name}
                                </Text>
                            </TouchableOpacity>
                        ))}
                        <TouchableOpacity
                            style={styles.addScheduleButton}
                            onPress={() => setIsAddingSchedule(true)}
                        >
                            <Text style={styles.addScheduleButtonText}>+</Text>
                        </TouchableOpacity>
                    </ScrollView>
                </View>
                {isAddingSchedule && (
                    <Animated.View style={styles.addScheduleInputContainer} entering={FadeIn.springify().damping(17)} exiting={FadeOut}>
                        <TextInput
                            style={styles.addScheduleInput}
                            value={scheduleName}
                            onChangeText={setScheduleName}
                            placeholder="New Schedule Name"
                            onSubmitEditing={addNewSchedule}
                        />
                        <TouchableOpacity onPress={addNewSchedule} style={styles.addButton}>
                            <Text style={styles.addButtonText}>Add</Text>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => setIsAddingSchedule(false)} style={styles.cancelButton}>
                            <Text style={styles.cancelButtonText}>Cancel</Text>
                        </TouchableOpacity>
                    </Animated.View>
                )}
                <View style={styles.outerCalendarContainer}>
                    <Timetable
                        items={currentSchedule.items}
                        range={range}
                        timeWidth={50}
                        hourHeight={40}
                        renderHeader={CustomHeader}
                        renderItem={props => {
                            const dayIndex = calculateDayIndex(props.item.startDate);
                            return (
                                <Rectangle 
                                    {...props} 
                                    dayIndex={dayIndex} 
                                    daysTotal={5} 
                                    index={props.index}
                                    event={currentSchedule[dayIndex - 1]} // Pass the event data
                                />
                            );
                        }}
                        is12Hour={true}
                        fromHour={8}
                        toHour={18}
                        style={styles.timetable}
                        columnWidth={700 / 5 - 1}
                        hideNowLine={true}
                    />
                </View>
                <View style={styles.searchButtonContainer}>
                    {
                        currentSchedule.items.length > 0 ? (
                            <ButtonComp title="Edit" buttonStyle={styles.searchButton} onPress={() => setOpen(true)} />
                        ) : (
                            <ButtonComp title="Create" buttonStyle={styles.searchButton} onPress={() => setOpen(true)} />
                        )
                    }
                    
                    <ButtonComp title="Save" buttonStyle={styles.searchButton} onPress={handleSave} />
                </View>
            </View>
            {isOpen && (
                <>
                    <AnimatedPressable onPress={() => setOpen(false)} style={styles.backdrop} entering={FadeIn} exiting={FadeOut} />
                    <Animated.View style={styles.sheet} entering={SlideInDown.springify().damping(17)} exiting={SlideOutDown.springify().damping(17)}>
                        <ScheduleEditor handleScheduleCreation={handleScheduleCreation} />
                    </Animated.View>
                </>
            )}
        </View>
    );
};



import React, { useState } from "react";
import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
import { Picker } from '@react-native-picker/picker';
import Button from "../common/Button";

const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
const hours = Array.from({length: 11}, (_, i) => {
    const hour = (i + 8) % 12 || 12; // Convert to 12-hour format
    const period = (i + 8) < 12 ? 'AM' : 'PM'; // Determine AM/PM
    return `${hour.toString().padStart(2, '0')} ${period}`;
});
const minutes = Array.from({length: 60}, (_, i) => i.toString().padStart(2, '0'));

const ScheduleEditor = ({ handleScheduleCreation }) => {
    const [selectedDays, setSelectedDays] = useState([]);
    const [startHour, setStartHour] = useState('08');
    const [startMinute, setStartMinute] = useState('00');
    const [startPeriod, setStartPeriod] = useState('AM');
    const [endHour, setEndHour] = useState('09');
    const [endMinute, setEndMinute] = useState('00');
    const [endPeriod, setEndPeriod] = useState('AM');

    const toggleDay = (day) => {
        setSelectedDays(prevDays => 
            prevDays.includes(day)
                ? prevDays.filter(d => d !== day)
                : [...prevDays, day]
        );
    };

    const convertTo24Hour = (hour, period) => {
        let hourInt = parseInt(hour);
        if (period === 'PM' && hourInt !== 12) {
            hourInt += 12;
        }
        return hourInt.toString().padStart(2, '0');
    };

    const handleSave = () => {
        const start24Hour = convertTo24Hour(startHour, startPeriod);
        console.log(start24Hour);
        const end24Hour = convertTo24Hour(endHour, endPeriod);
        console.log(end24Hour);
        handleScheduleCreation(selectedDays, start24Hour, startMinute, end24Hour, endMinute);
    };

    return (
        <View style={styles.container}>
            <View style={styles.dayButtonsContainer}>
                {days.map((day) => (
                    <TouchableOpacity
                        key={day}
                        style={[
                            styles.dayButton,
                            selectedDays.includes(day) && styles.selectedDayButton
                        ]}
                        onPress={() => toggleDay(day)}
                    >
                        <Text style={[
                            styles.dayButtonText,
                            selectedDays.includes(day) && styles.selectedDayButtonText
                        ]}>
                            {day}
                        </Text>
                    </TouchableOpacity>
                ))}
            </View>
            <View style={styles.timeContainer}>
                <View style={styles.pickerContainer}>
                    <Text style={styles.pickerLabel}>Start Time</Text>
                    <View style={styles.pickerRow}>
                        <View style={styles.pickerWrapper}>
                            <Picker
                                selectedValue={startHour}
                                onValueChange={(itemValue) => setStartHour(itemValue)}
                                style={styles.picker}
                            >
                                {hours.map((hour) => (
                                    <Picker.Item key={`start-hour-${hour}`} label={hour.split(' ')[0]} value={hour.split(' ')[0]} style={styles.pickerItem} />
                                ))}
                            </Picker>
                        </View>
                        <Text style={styles.pickerSeparator}>:</Text>
                        <View style={styles.pickerWrapper}>
                            <Picker
                                selectedValue={startMinute}
                                onValueChange={(itemValue) => setStartMinute(itemValue)}
                                style={styles.picker}
                            >
                                {minutes.map((minute) => (
                                    <Picker.Item key={`start-minute-${minute}`} label={minute} value={minute} style={styles.pickerItem} />
                                ))}
                            </Picker>
                        </View>
                        <View style={styles.AMPMContainer}>
                            <TouchableOpacity style={[styles.AMPMButton, startPeriod === 'AM' && styles.activeAMPMButton]} onPress={() => setStartPeriod('AM')}>
                                <Text style={startPeriod === 'AM' && styles.activeAMPMText}>AM</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[styles.AMPMButton, startPeriod === 'PM' && styles.activeAMPMButton]} onPress={() => setStartPeriod('PM')}>
                                <Text style={startPeriod === 'PM' && styles.activeAMPMText}>PM</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                <View style={styles.pickerContainer}>
                    <Text style={styles.pickerLabel}>End Time</Text>
                    <View style={styles.pickerRow}>
                        <View style={styles.pickerWrapper}>
                            <Picker
                                selectedValue={endHour}
                                onValueChange={(itemValue) => setEndHour(itemValue)}
                                style={styles.picker}
                            >
                                {hours.map((hour) => (
                                    <Picker.Item key={`end-hour-${hour}`} label={hour.split(' ')[0]} value={hour.split(' ')[0]} />
                                ))}
                            </Picker>
                        </View>
                        <Text style={styles.pickerSeparator}>:</Text>
                        <View style={styles.pickerWrapper}>
                            <Picker
                                selectedValue={endMinute}
                                onValueChange={(itemValue) => setEndMinute(itemValue)}
                                style={styles.picker}
                            >
                                {minutes.map((minute) => (
                                    <Picker.Item key={`end-minute-${minute}`} label={minute} value={minute} />
                                ))}
                            </Picker>
                        </View>
                        <View style={styles.AMPMContainer}>
                            <TouchableOpacity style={[styles.AMPMButton, endPeriod === 'AM' && styles.activeAMPMButton]} onPress={() => setEndPeriod('AM')}>
                                <Text style={endPeriod === 'AM' && styles.activeAMPMText}>AM</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[styles.AMPMButton, endPeriod === 'PM' && styles.activeAMPMButton]} onPress={() => setEndPeriod('PM')}>
                                <Text style={endPeriod === 'PM' && styles.activeAMPMText}>PM</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={styles.buttonContainer}>   
                        <Button title="Apply" onPress={handleSave} style={styles.modalButtonContainer} buttonStyle={styles.modalButton}/>
                    </View>
                </View>
            </View>
        </View>
    );
};


The first piece of code is my scheduling interface. The second piece of code is modal I bring up to customize my shcheduling interface. I have a lot of state in the first piece of code but I am having trouble understanding the order of the state updates in an organized way in my mind. Could you systematically help me track how state is moving through both components and explain the fundamentals of state in react as reasoning behind the state updates. I want to get a clear picture of state in my mind for these components.