import React, { useState } from "react";
import {
  format,
  startOfMonth,
  endOfMonth,
  startOfWeek,
  endOfWeek,
  eachDayOfInterval,
  addMonths,
  subMonths,
  isSameMonth,
  isSameDay,
} from "date-fns";
import { ru } from "date-fns/locale";
import { useAppSelector, useAppDispatch } from "../../store/hooks";
import { setSelectedDate } from "../../store/slices/notesSlice";
import { formatDateFromTimestamp } from "../../utils/dateFormat";
import { Note } from "../../types/note";

interface MiniCalendarProps {
  notes?: Note[];
}

export const MiniCalendar: React.FC<MiniCalendarProps> = ({ notes = [] }) => {
  const [currentDate, setCurrentDate] = useState(new Date());
  const selectedDate = useAppSelector((state) => state.notes.selectedDate);
  const dispatch = useAppDispatch();

  const monthStart = startOfMonth(currentDate);
  const monthEnd = endOfMonth(currentDate);
  const calendarStart = startOfWeek(monthStart, { weekStartsOn: 1 });
  const calendarEnd = endOfWeek(monthEnd, { weekStartsOn: 1 });

  const days = eachDayOfInterval({ start: calendarStart, end: calendarEnd });

  // Получаем даты с заметками
  const createdNoteDates = new Set<string>();
  const editedNoteDates = new Set<string>();

  notes.forEach((note) => {
    if (note.created_at) {
      createdNoteDates.add(formatDateFromTimestamp(note.created_at));
    }
    if (note.updated_at && note.created_at !== note.updated_at) {
      editedNoteDates.add(formatDateFromTimestamp(note.updated_at));
    }
  });

  const handleDayClick = (day: Date) => {
    const dateStr = format(day, "dd.MM.yyyy");
    if (selectedDate === dateStr) {
      dispatch(setSelectedDate(null));
    } else {
      dispatch(setSelectedDate(dateStr));
    }
  };

  const handlePrevMonth = () => {
    setCurrentDate(subMonths(currentDate, 1));
  };

  const handleNextMonth = () => {
    setCurrentDate(addMonths(currentDate, 1));
  };

  const monthYear = format(currentDate, "MMMM yyyy", { locale: ru });
  const capitalizedMonthYear =
    monthYear.charAt(0).toUpperCase() + monthYear.slice(1);

  return (
    <div className="mini-calendar">
      <div className="calendar-header">
        <button className="calendar-nav" onClick={handlePrevMonth}>
          ‹
        </button>
        <span className="calendar-month-year">{capitalizedMonthYear}</span>
        <button className="calendar-nav" onClick={handleNextMonth}>
          ›
        </button>
      </div>
      <div className="calendar-weekdays">
        <div className="calendar-weekday">Пн</div>
        <div className="calendar-weekday">Вт</div>
        <div className="calendar-weekday">Ср</div>
        <div className="calendar-weekday">Чт</div>
        <div className="calendar-weekday">Пт</div>
        <div className="calendar-weekday">Сб</div>
        <div className="calendar-weekday">Вс</div>
      </div>
      <div className="calendar-days">
        {days.map((day, index) => {
          const dateStr = format(day, "dd.MM.yyyy");
          const isCurrentMonth = isSameMonth(day, currentDate);
          const isSelected = selectedDate === dateStr;
          const hasNotes = createdNoteDates.has(dateStr);
          const hasEditedNotes = editedNoteDates.has(dateStr);
          const isToday = isSameDay(day, new Date());

          return (
            <div
              key={index}
              className={`calendar-day ${
                !isCurrentMonth ? "other-month" : ""
              } ${hasNotes ? "has-notes" : ""} ${
                hasEditedNotes ? "has-edited-notes" : ""
              } ${isSelected ? "selected" : ""} ${isToday ? "today" : ""}`}
              data-date={dateStr}
              onClick={() => handleDayClick(day)}
            >
              {format(day, "d")}
            </div>
          );
        })}
      </div>
    </div>
  );
};
