import React, {useState, useRef, useEffect} from 'react';
import {DeviceEventEmitter, PanResponder} from 'react-native';
import FilterDateView from './view';

const FilterDate = ({navigation}) => {
  const [currentDate, setCurrentDate] = useState(new Date(2025, 6, 24));
  const [selectedDate, setSelectedDate] = useState(new Date(2025, 6, 24));
  const [showMonthPicker, setShowMonthPicker] = useState(false);
  const scrollViewRef = useRef(null);

  useEffect(() => {
    DeviceEventEmitter.emit('onDateChange', selectedDate);
  }, [selectedDate]);

  const createMockEvents = () => {
    return [
      {
        id: '1',
        title: 'Lịch vào trực lớp TTCĐT 445.T1',
        subtitle: 'CS Địa lý 4D',
        time: '07:00',
        endTime: '09:00',
        date: '2025-07-24',
        type: 'class',
      },
      {
        id: '2',
        title: 'Meeting team development',
        subtitle: 'Phòng họp A1',
        time: '10:00',
        endTime: '11:30',
        date: '2025-07-24',
        type: 'meeting',
      },
      {
        id: '3',
        title: 'Training React Native',
        subtitle: 'Online Zoom',
        time: '14:00',
        endTime: '16:00',
        date: '2025-07-25',
        type: 'training',
      },
    ];
  };

  const mockEvents = createMockEvents();

  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 getEventsForDate = (date) => {
    const dateStr = formatDateToString(date);
    return mockEvents.filter(event => event.date === dateStr);
  };

  const getDayName = (date) => {
    const days = ['Chủ nhật', 'Thứ 2', 'Thứ 3', 'Thứ 4', 'Thứ 5', 'Thứ 6', 'Thứ 7'];
    return days[date.getDay()];
  };

  const getMonthName = (monthIndex) => {
    const months = [
      '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 months[monthIndex];
  };

  const handleMonthSelect = (monthIndex) => {
    const newDate = new Date(currentDate);
    newDate.setMonth(monthIndex);
    setCurrentDate(newDate);
    setSelectedDate(newDate);
    setShowMonthPicker(false);
    DeviceEventEmitter.emit('onDateChange', newDate);
  };

  const swipeToNextDay = () => {
    const nextDay = new Date(selectedDate);
    nextDay.setDate(selectedDate.getDate() + 1);
    setSelectedDate(nextDay);
    setCurrentDate(nextDay);
    DeviceEventEmitter.emit('onDateChange', nextDay);
  };

  const swipeToPrevDay = () => {
    const prevDay = new Date(selectedDate);
    prevDay.setDate(selectedDate.getDate() - 1);
    setSelectedDate(prevDay);
    setCurrentDate(prevDay);
    DeviceEventEmitter.emit('onDateChange', prevDay);
  };

  const toggleMonthPicker = () => {
    setShowMonthPicker(!showMonthPicker);
  };

  const panResponder = PanResponder.create({
    onMoveShouldSetPanResponder: (evt, gestureState) => {
      return Math.abs(gestureState.dx) > 30 && Math.abs(gestureState.dy) < 100;
    },
    onPanResponderMove: (evt, gestureState) => {},
    onPanResponderRelease: (evt, gestureState) => {
      if (gestureState.dx > 50) {
        swipeToPrevDay();
      } else if (gestureState.dx < -50) {
        swipeToNextDay();
      }
    },
  });

  const calculateEventPosition = (startTime, endTime) => {
    const [startHour, startMinute] = startTime.split(':').map(Number);
    const [endHour, endMinute] = endTime.split(':').map(Number);
    
    const startTotalMinutes = startHour * 60 + startMinute;
    const endTotalMinutes = endHour * 60 + endMinute;
    const durationMinutes = endTotalMinutes - startTotalMinutes;
    
    const HOUR_HEIGHT = 80;
    const topPosition = (startTotalMinutes / 60) * HOUR_HEIGHT;
    const height = (durationMinutes / 60) * HOUR_HEIGHT;
    
    return { topPosition, height };
  };

  return (
    <FilterDateView
      navigation={navigation}
      currentDate={currentDate}
      selectedDate={selectedDate}
      showMonthPicker={showMonthPicker}
      scrollViewRef={scrollViewRef}
      panResponder={panResponder}
      getEventsForDate={getEventsForDate}
      getDayName={getDayName}
      getMonthName={getMonthName}
      handleMonthSelect={handleMonthSelect}
      toggleMonthPicker={toggleMonthPicker}
      calculateEventPosition={calculateEventPosition}
    />
  );
};

export default FilterDate;