// hooks/useFilterDay.js
import { useState, useRef, useEffect, useCallback } from 'react';
import { DeviceEventEmitter, PanResponder } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { HOUR_HEIGHT, DAYS_SHORT, MONTHS_VI } from '../config/constants';
import { formatDateToString,  layoutDayEvents} from '../config/Functions';

export const useFilterDay = (initialEvents) => {
  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]);

  
  useFocusEffect(
    useCallback(() => {
      const today = new Date();
      setCurrentDate(today);
      setSelectedDate(today);
      DeviceEventEmitter.emit('onDateChange', today);
      DeviceEventEmitter.emit('updateHeaderMonth', today.getMonth());
    }, [])
  );

  const getEventsForDate = useCallback((date) => {
    const dateStr = formatDateToString(date);
    return initialEvents.filter(e => e.date === dateStr);
  }, [initialEvents]);

  const getDayName = (date) => DAYS_SHORT[date.getDay()];
  const getMonthName = (i) => MONTHS_VI[i];

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

  const setDay = (d) => {
    setSelectedDate(d);
    setCurrentDate(d);
    DeviceEventEmitter.emit('onDateChange', d);
    DeviceEventEmitter.emit('updateHeaderMonth', d.getMonth());
  };

  const swipeToNextDay = () => {
    const next = new Date(selectedDate);
    next.setDate(selectedDate.getDate() + 1);
    setDay(next);
  };

  const swipeToPrevDay = () => {
    const prev = new Date(selectedDate);
    prev.setDate(selectedDate.getDate() - 1);
    setDay(prev);
  };

  const toggleMonthPicker = () => setShowMonthPicker(v => !v);

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

  const calculateEventPosition = (start, end) => {
    const [sh, sm] = start.split(':').map(Number);
    const [eh, em] = end.split(':').map(Number);
    const startMin = sh * 60 + sm;
    const endMin = eh * 60 + em;
    const topPosition = (startMin / 60) * HOUR_HEIGHT;
    const height = ((endMin - startMin) / 60) * HOUR_HEIGHT;
    return { topPosition, height };
  };

  const calculateEventLayout = useCallback((events) => {
    return layoutDayEvents(events, HOUR_HEIGHT);
  }, []);

  return {
    // state
    currentDate, selectedDate, showMonthPicker, scrollViewRef,
    // getters
    getEventsForDate, getDayName, getMonthName,
    // actions
    handleMonthSelect, toggleMonthPicker,
    swipeToNextDay, swipeToPrevDay,
    // gestures
    panResponder,
    // layout
    calculateEventPosition, calculateEventLayout,
  };
};
