import React from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Dimensions,
  Modal,
  Animated,
  SafeAreaView,
} from 'react-native';
import R from '../../assets/R';
import { styles, CELL_WIDTH, BOTTOM_SHEET_HEIGHT } from './style';
import { useNavigation } from '@react-navigation/native';
import * as SCREENNAME from '../../routers/ScreenNames';

const ClassScheduleView = ({
  currentDate,
  selectedDate,
  showBottomSheet,
  bottomSheetTranslateY,
  panResponder,
  getMonthData,
  getEventsForDate,
  parseLocalDate,
  formatDateToDisplay,
  isCurrentMonth,
  isToday,
  navigateMonth,
  handleDatePress,
  handleEventPress,
  handleCloseBottomSheet,
  getSelectedEvents,
}) => {
  const navigation = useNavigation();
  const renderHeader = () => {
    const monthNames = [
      'Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 5', 'Tháng 6',
      'Tháng 7', 'Tháng 8', 'Tháng 9', 'Tháng 10', 'Tháng 11', 'Tháng 12',
    ];

    return (
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.navButton}
          onPress={() => navigateMonth('prev')}>
          <Text style={styles.navButtonText}>‹</Text>
        </TouchableOpacity>

        <Text style={styles.header_title}>
          {monthNames[getMonthData.month]} {getMonthData.year}
        </Text>

        <TouchableOpacity
          style={styles.navButton}
          onPress={() => navigateMonth('next')}>
          <Text style={styles.navButtonText}>›</Text>
        </TouchableOpacity>
      </View>
    );
  };

  const renderWeekDays = () => {
    const weekDays = ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'];

    return (
      <View style={styles.weekDaysContainer}>
        {weekDays.map((day, index) => (
          <View key={index} style={styles.weekDayCell}>
            <Text style={styles.weekDayText}>{day}</Text>
          </View>
        ))}
      </View>
    );
  };

  const renderDayCell = (date, index) => {
    const dayEvents = getEventsForDate(date);
    const isSelected = selectedDate === formatDateToString(date);
    const isTodayDate = isToday(date);
    const isInCurrentMonth = isCurrentMonth(date);

    return (
      <TouchableOpacity
        key={index}
        style={[
          styles.dayCell,
          isSelected && styles.selectedDayCell,
          isTodayDate && styles.todayCell,
        ]}
        onPress={() => handleDatePress(date)}
        activeOpacity={0.7}>

        <Text
          style={[
            styles.dayText,
            !isInCurrentMonth && styles.dayTextInactive,
            isSelected && styles.selectedDayText,
            isTodayDate && styles.todayText,
          ]}>
          {date.getDate()}
        </Text>

        {dayEvents.length > 0 && (
          <View style={styles.eventsContainer}>
            {dayEvents.slice(0, 2).map((event, eventIndex) => (
              <TouchableOpacity
                key={event.id}
                style={[
                  styles.eventBar,
                  { backgroundColor: R.colors.main },
                ]}
                onPress={() => handleEventPress(event)}>
                <Text style={styles.eventBarText} numberOfLines={1}>
                  {event.title}
                </Text>
              </TouchableOpacity>
            ))}
            {dayEvents.length > 2 && (
              <Text style={styles.moreEventsText}>+{dayEvents.length - 2}</Text>
            )}
          </View>
        )}
      </TouchableOpacity>
    );
  };

  const formatDateToString = (date) => {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  };


  const renderCalendarGrid = () => {
    const weeks = [];
    for (let i = 0; i < 6; i++) {
      const week = getMonthData.days.slice(i * 7, (i + 1) * 7);
      weeks.push(
        <View key={i} style={styles.weekRow}>
          {week.map((date, dayIndex) =>
            renderDayCell(date, i * 7 + dayIndex),
          )}
        </View>,
      );
    }
    return <View style={styles.calendarGrid}>{weeks}</View>;
  };

  const renderBottomSheetContent = () => {
    if (!selectedDate) return null;

    const selectedDateObj = parseLocalDate(selectedDate);
    const selectedEvents = getSelectedEvents();

    return (
      <View style={styles.bottomSheetContent}>
        <View style={styles.dragHandle} />

        <View style={styles.bottomSheetHeader}>
          <Text style={styles.bottomSheetTitle}>
            {formatDateToDisplay(selectedDateObj)}
          </Text>
          <TouchableOpacity
            style={styles.closeButton}
            onPress={handleCloseBottomSheet}>
            <Text style={styles.closeButtonText}>✕</Text>
          </TouchableOpacity>
        </View>

        <ScrollView
          style={styles.eventsScrollView}
          showsVerticalScrollIndicator={false}>
          {selectedEvents.length === 0 ? (
            <View style={styles.noEventsContainer}>
              <Text style={styles.noEventsText}>Không có sự kiện nào</Text>
            </View>
          ) : (
            selectedEvents.map((event, index) => (
              <TouchableOpacity
                key={event.id}
                style={styles.eventCard}
                onPress={() => navigation.navigate(SCREENNAME.DETAILCLASSSCHEDULE, { event })}
                activeOpacity={0.7}>

                <View style={styles.eventTimeContainer}>
                  <Text style={styles.eventTime}>
                    {event.time}
                    {event.endTime && ` - ${event.endTime}`}
                  </Text>
                </View>

                <View style={styles.eventContent}>
                  <Text style={styles.eventTitle} numberOfLines={2}>
                    {event.title}
                  </Text>
                  {event.description && (
                    <Text style={styles.eventDescription} numberOfLines={3}>
                      {event.description}
                    </Text>
                  )}
                </View>
              </TouchableOpacity>
            ))
          )}
        </ScrollView>
      </View>
    );
  };

  const renderBottomSheet = () => {
    return (
      <Modal
        visible={showBottomSheet}
        transparent={true}
        animationType="none"
        onRequestClose={handleCloseBottomSheet}>

        <TouchableOpacity
          style={styles.modalBackdrop}
          activeOpacity={1}
          onPress={handleCloseBottomSheet}>

          <Animated.View
            style={[
              styles.bottomSheet,
              {
                transform: [{ translateY: bottomSheetTranslateY }],
              },
            ]}
            {...panResponder.panHandlers}>
            <TouchableOpacity activeOpacity={1}>
              {renderBottomSheetContent()}
            </TouchableOpacity>
          </Animated.View>
        </TouchableOpacity>
      </Modal>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView showsVerticalScrollIndicator={false}>
        {renderHeader()}
        {renderWeekDays()}
        {renderCalendarGrid()}
      </ScrollView>
      {renderBottomSheet()}
    </SafeAreaView>
  );
};



export default ClassScheduleView;