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

LogBox.ignoreLogs([
  '[Reanimated] Reduced motion setting is enabled', 
]);
const ClassScheduleView = ({
  currentDate,
  selectedDate,
  showBottomSheet,
  bottomSheetTranslateY,
  panResponder,
  getMonthData,
  getEventsForDate,
  parseLocalDate,
  formatDateToDisplay,
  formatDateToString,
  isCurrentMonth,
  isToday,
  navigateMonth,
  handleDatePress,
  handleEventPress,
  handleCloseBottomSheet,
  getSelectedEvents,
}) => {
  const navigation = useNavigation();

  // Tạo PanResponder cho swipe gesture điều hướng tháng
  const swipePanResponder = PanResponder.create({
    onMoveShouldSetPanResponder: (evt, gestureState) => {
      // Chỉ kích hoạt khi vuốt ngang với khoảng cách đủ lớn
      return Math.abs(gestureState.dx) > Math.abs(gestureState.dy) && Math.abs(gestureState.dx) > 20;
    },
    onPanResponderMove: (evt, gestureState) => {
      // Có thể thêm animation preview ở đây nếu cần
    },
    onPanResponderRelease: (evt, gestureState) => {
      const swipeThreshold = 50; // Ngưỡng tối thiểu để kích hoạt swipe
      
      if (gestureState.dx > swipeThreshold) {
        // Vuốt phải -> tháng trước
        navigateMonth('prev');
      } else if (gestureState.dx < -swipeThreshold) {
        // Vuốt trái -> tháng sau
        navigateMonth('next');
      }
    },
  });
  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, formatDateToString) => {
    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,
          !isInCurrentMonth && {backgroundColor: R.colors.gray},
        ]}
        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]}
                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 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, formatDateToString),
          )}
        </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>

        <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) => (
              <View style={styles.containerBottomSheet}>
                <TouchableOpacity
                  key={event.id}
                  style={styles.eventCard}
                  onPress={() =>
                    navigation.navigate(SCREENNAME.DETAILSCHEDULE, {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>
              </View>
            ))
          )}
        </ScrollView>
      </View>
    );
  };

  // ===== RENDER BOTTOM SHEET - Modal bottom sheet =====
  // Sử dụng styles: modalBackdrop, bottomSheet
  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>
    );
  };

  // ===== MAIN RENDER - Render chính của component =====
  // Sử dụng styles: container
  return (
    <View style={styles.container}>
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={styles.body} {...swipePanResponder.panHandlers}>
          {renderHeader()}
          {renderWeekDays()}
          {renderCalendarGrid()}
        </View>
      </ScrollView>
      {renderBottomSheet()}
    </View>
  );
};

export default ClassScheduleView;
