import React, {useState, useMemo, useRef} from 'react';
import {Animated, PanResponder, Dimensions} from 'react-native';
import ClassScheduleView from './view';

const {height: screenHeight} = Dimensions.get('window');
const BOTTOM_SHEET_HEIGHT = screenHeight * 0.6;

const ClassSchedule = ({events = [], onDateSelect, onEventPress}) => {
  const [currentDate, setCurrentDate] = useState(new Date(2025, 7, 1));
  const [selectedDate, setSelectedDate] = useState(null);
  const [showBottomSheet, setShowBottomSheet] = useState(false);
  
  const bottomSheetTranslateY = useRef(new Animated.Value(BOTTOM_SHEET_HEIGHT)).current;

  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 createMockEvents = () => {
    const today = new Date();
    const todayStr = formatDateToString(today);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const tomorrowStr = formatDateToString(tomorrow);

    return [
      {
        id: '1',
        title: 'Meeting hôm nay',
        date: todayStr,
        time: '10:00',
        endTime: '11:00',
        description: 'Họp team development',
        type: 'meeting',
      },
      {
        id: '2',
        title: 'Demo hôm nay',
        date: todayStr,
        time: '15:00',
        endTime: '16:00',
        description: 'Present tính năng mới',
        type: 'demo',
      },
      {
        id: '11',
        title: 'Lịch học lớp IT47.8F7',
        date: '2025-08-04',
        time: '07:00',
        endTime: '08:30',
        description: 'Môn học chuyên ngành',
        type: 'class',
      },
      {
        id: '12',
        title: 'Meeting team',
        date: '2025-08-04',
        time: '10:00',
        endTime: '11:00',
        description: 'Họp team development',
        type: 'meeting',
      },
      {
        id: '13',
        title: 'Training React Native',
        date: '2025-08-05',
        time: '14:00',
        endTime: '16:00',
        description: 'Học New Architecture',
        type: 'training',
      },
      {
        id: '14',
        title: 'Code Review',
        date: '2025-08-05',
        time: '10:30',
        endTime: '11:30',
        description: 'Review PR #123',
        type: 'review',
      },
      {
        id: '15',
        title: 'Họp nội bộ giữa giảng viên bộ môn công nghệ phần mềm',
        date: '2025-08-05',
        time: '09:00',
        endTime: '11:30',
        description: 'Thảo luận chương trình đào tạo mới',
        type: 'meeting',
      },
      {
        id: '16',
        title: 'Sự kiện thắp sáng ước mơ kỹ thuật',
        date: '2025-08-05',
        time: '13:00',
        endTime: '15:30',
        description: 'Chương trình định hướng nghề nghiệp cho sinh viên',
        type: 'event',
      },
      {
        id: '17',
        title: 'Lịch học lớp EWC45.364.L1',
        date: '2025-08-05',
        time: '14:00',
        endTime: '15:30',
        description: 'Tiếng Anh chuyên ngành',
        type: 'class',
      },
      {
        id: '18',
        title: 'Họp tổng kết quả chấm nghiệm cứu khoa học sinh viên khóa K18',
        date: '2025-08-05',
        time: '17:00',
        endTime: '20:30',
        description: 'Đánh giá kết quả nghiên cứu khoa học của sinh viên',
        type: 'meeting',
      },
      {
        id: '3',
        title: 'Training React Native',
        date: tomorrowStr,
        time: '14:00',
        endTime: '16:00',
        description: 'Học New Architecture',
        type: 'training',
      },
      {
        id: '4',
        title: 'Code Review',
        date: tomorrowStr,
        time: '10:30',
        endTime: '11:30',
        description: 'Review PR #123',
        type: 'review',
      },
      {
        id: '10',
        title: 'Demo sản phẩm',
        date: '2025-08-25',
        time: '15:00',
        endTime: '16:30',
        description: 'Present tính năng mới',
        type: 'demo',
      },
    ];
  };

  const mockEvents = createMockEvents();
  const allEvents = [...events, ...mockEvents];

  const panResponder = useRef(
    PanResponder.create({
      onMoveShouldSetPanResponder: (evt, gestureState) => {
        return Math.abs(gestureState.dy) > 10;
      },
      onPanResponderMove: (evt, gestureState) => {
        if (gestureState.dy > 0) {
          bottomSheetTranslateY.setValue(gestureState.dy);
        }
      },
      onPanResponderRelease: (evt, gestureState) => {
        if (gestureState.dy > 100) {
          hideBottomSheetModal();
        } else {
          Animated.spring(bottomSheetTranslateY, {
            toValue: 0,
            useNativeDriver: true,
          }).start();
        }
      },
    })
  ).current;

  const getMonthData = useMemo(() => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const startDate = new Date(firstDay);
    startDate.setDate(firstDay.getDate() - firstDay.getDay());

    const days = [];
    const currentDateObj = new Date(startDate);

    for (let i = 0; i < 42; i++) {
      days.push(new Date(currentDateObj));
      currentDateObj.setDate(currentDateObj.getDate() + 1);
    }

    return {
      year,
      month,
      firstDay,
      lastDay,
      days,
    };
  }, [currentDate]);

  const getEventsForDate = (date) => {
    const dateStr = formatDateToString(date);
    return allEvents.filter(event => event.date === dateStr);
  };

  const parseLocalDate = (dateString) => {
    const [year, month, day] = dateString.split('-').map(Number);
    return new Date(year, month - 1, day);
  };

  const formatDateToDisplay = (date) => {
    const day = date.getDate().toString().padStart(2, '0');
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const year = date.getFullYear();
    return `Lịch ngày ${day}/${month}/${year}`;
  };

  const isCurrentMonth = (date) => {
    return date.getMonth() === currentDate.getMonth();
  };

  const isToday = (date) => {
    const today = new Date();
    return (
      date.getDate() === today.getDate() &&
      date.getMonth() === today.getMonth() &&
      date.getFullYear() === today.getFullYear()
    );
  };

  const navigateMonth = (direction) => {
    const newDate = new Date(currentDate);
    if (direction === 'prev') {
      newDate.setMonth(newDate.getMonth() - 1);
    } else {
      newDate.setMonth(newDate.getMonth() + 1);
    }
    setCurrentDate(newDate);
    setSelectedDate(null);
    if (showBottomSheet) {
      hideBottomSheetModal();
    }
  };

  const showBottomSheetModal = () => {
    setShowBottomSheet(true);
    Animated.spring(bottomSheetTranslateY, {
      toValue: 0,
      tension: 100,
      friction: 8,
      useNativeDriver: true,
    }).start();
  };

  const hideBottomSheetModal = () => {
    Animated.timing(bottomSheetTranslateY, {
      toValue: BOTTOM_SHEET_HEIGHT,
      duration: 300,
      useNativeDriver: true,
    }).start(() => {
      setShowBottomSheet(false);
    });
  };

  const handleDatePress = (date) => {
    const dateStr = formatDateToString(date);
    const dayEvents = getEventsForDate(date);
    
    setSelectedDate(dateStr);
    onDateSelect?.(dateStr);

    if (dayEvents.length > 0) {
      showBottomSheetModal();
    }
  };

  const handleEventPress = (event) => {
    onEventPress?.(event);
  };

  const handleCloseBottomSheet = () => {
    hideBottomSheetModal();
  };

  const getSelectedEvents = () => {
    if (!selectedDate) return [];
    return allEvents
      .filter(event => event.date === selectedDate)
      .sort((a, b) => a.time.localeCompare(b.time));
  };

  return (
    <ClassScheduleView
      currentDate={currentDate}
      selectedDate={selectedDate}
      showBottomSheet={showBottomSheet}
      bottomSheetTranslateY={bottomSheetTranslateY}
      panResponder={panResponder}
      getMonthData={getMonthData}
      getEventsForDate={getEventsForDate}
      parseLocalDate={parseLocalDate}
      formatDateToDisplay={formatDateToDisplay}
      isCurrentMonth={isCurrentMonth}
      isToday={isToday}
      navigateMonth={navigateMonth}
      handleDatePress={handleDatePress}
      handleEventPress={handleEventPress}
      handleCloseBottomSheet={handleCloseBottomSheet}
      getSelectedEvents={getSelectedEvents}
    />
  );
};

export default ClassSchedule;