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

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

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

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

  const createMockEvents = () => {
    return [
      {
        id: '1',
        title: 'Lịch vào trực lớp TTCĐT 445.T1',
        subtitle: 'CS lớp 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-25',
        type: 'meeting',
      },
      {
        id: '3',
        title: 'Training React Native',
        subtitle: 'Online Zoom',
        time: '14:00',
        endTime: '16:00',
        date: '2025-07-26',
        type: 'training',
      },
      {
        id: '4',
        title: 'Code Review Session',
        subtitle: 'Dev Team',
        time: '09:30',
        endTime: '11:30',
        date: '2025-08-25',
        type: 'review',
      },
    ];
  };

  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 get3DaysDates = (date) => {
    const dates = [];
    for (let i = 0; i < 3; i++) {
      const dayDate = new Date(date);
      dayDate.setDate(date.getDate() + i);
      dates.push(dayDate);
    }
    return dates;
  };

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

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

  const swipeToNext3Days = () => {
    const nextDate = new Date(currentDate);
    nextDate.setDate(currentDate.getDate() + 3);
    setCurrentDate(nextDate);
    setSelectedDate(nextDate);
    DeviceEventEmitter.emit('onDateChange', nextDate);
  };

  const swipeToPrev3Days = () => {
    const prevDate = new Date(currentDate);
    prevDate.setDate(currentDate.getDate() - 3);
    setCurrentDate(prevDate);
    setSelectedDate(prevDate);
    DeviceEventEmitter.emit('onDateChange', prevDate);
  };

  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) {
        swipeToPrev3Days();
      } else if (gestureState.dx < -50) {
        swipeToNext3Days();
      }
    },
  });

  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 (
    <Filter3DayView 
      navigation={navigation}
      currentDate={currentDate}
      selectedDate={selectedDate}
      showMonthPicker={showMonthPicker}
      scrollViewRef={scrollViewRef}
      panResponder={panResponder}
      getEventsForDate={getEventsForDate}
      getDayName={getDayName}
      getMonthName={getMonthName}
      get3DaysDates={get3DaysDates}
      isToday={isToday}
      handleMonthSelect={handleMonthSelect}
      toggleMonthPicker={toggleMonthPicker}
      calculateEventPosition={calculateEventPosition}
    />
  );
};

export default Filter3Day;
