import { useMemo } from 'react';
import { format, startOfMonth, endOfMonth, addMonths, subMonths } from 'date-fns';
import useSWR, { mutate } from 'swr';

import {
  getCalendarLessons,
  getMentorStudents,
  getMentorSubjects,
  createCalendarLesson,
  updateCalendarLesson,
  deleteCalendarLesson,
} from 'src/utils/dashboard-api';

// ----------------------------------------------------------------------

const STUDENTS_ENDPOINT = '/manage/clients/?page=1&page_size=200';
const SUBJECTS_ENDPOINT = '/schedule/subjects/';

const swrOptions = {
  revalidateIfStale: true,
  revalidateOnFocus: false,
  revalidateOnReconnect: true,
};

// Ключ кэша для календаря (по месяцу)
function calendarKey(date = new Date()) {
  const start = format(startOfMonth(subMonths(date, 1)), 'yyyy-MM-dd');
  const end = format(endOfMonth(addMonths(date, 1)), 'yyyy-MM-dd');
  return ['calendar', start, end];
}

// ----------------------------------------------------------------------

export function useGetEvents(currentDate) {
  const date = currentDate || new Date();
  const start = format(startOfMonth(subMonths(date, 1)), 'yyyy-MM-dd');
  const end = format(endOfMonth(addMonths(date, 1)), 'yyyy-MM-dd');

  const { data: response, isLoading, error, isValidating } = useSWR(
    ['calendar', start, end],
    ([, s, e]) => getCalendarLessons(s, e),
    swrOptions
  );

  const memoizedValue = useMemo(() => {
    const lessonsArray = response?.data?.lessons || response?.lessons || [];

    const events = lessonsArray.map((lesson) => {
      const start = lesson.start_time || lesson.start;
      const end = lesson.end_time || lesson.end || start;

      const startTimeStr = start
        ? new Date(start).toLocaleTimeString('ru-RU', {
            hour: '2-digit',
            minute: '2-digit',
            hourCycle: 'h23',
          })
        : '';

      const subject = lesson.subject_name || lesson.subject || 'Урок';
      const student = lesson.client_name || '';
      const displayTitle = `${startTimeStr} ${subject}${student ? ` - ${student}` : ''}`;

      const status = String(lesson.status || 'scheduled').toLowerCase();
      let eventColor = '#7635dc';
      if (status === 'completed') eventColor = '#00ab55';
      else if (status === 'cancelled') eventColor = '#ff4842';
      else if (status === 'in_progress') eventColor = '#1890ff';

      return {
        id: String(lesson.id),
        title: displayTitle,
        start,
        end,
        allDay: false,
        color: eventColor,
        backgroundColor: eventColor,
        borderColor: eventColor,
        textColor: '#FFFFFF',
        extendedProps: {
          ...lesson,
          status,
          student: lesson.client_name || '',
          mentor: lesson.mentor_name || '',
        },
      };
    });

    return {
      events,
      eventsLoading: isLoading,
      eventsError: error,
      eventsValidating: isValidating,
      eventsEmpty: !isLoading && !events.length,
    };
  }, [response, error, isLoading, isValidating]);

  return memoizedValue;
}

// ----------------------------------------------------------------------

export function useGetStudents() {
  const { data: response, isLoading, error } = useSWR(
    STUDENTS_ENDPOINT,
    getMentorStudents,
    swrOptions
  );

  return useMemo(() => {
    const rawData = response?.data?.results || response?.results || response || [];
    return {
      students: Array.isArray(rawData) ? rawData : [],
      studentsLoading: isLoading,
      studentsError: error,
    };
  }, [response, isLoading, error]);
}

export function useGetSubjects() {
  const { data: response, isLoading, error } = useSWR(
    SUBJECTS_ENDPOINT,
    getMentorSubjects,
    swrOptions
  );

  return useMemo(() => {
    const rawData = response?.data || response?.results || response || [];
    return {
      subjects: Array.isArray(rawData) ? rawData : [],
      subjectsLoading: isLoading,
      subjectsError: error,
    };
  }, [response, isLoading, error]);
}

// ----------------------------------------------------------------------

function revalidateCalendar(date) {
  const d = date || new Date();
  const start = format(startOfMonth(subMonths(d, 1)), 'yyyy-MM-dd');
  const end = format(endOfMonth(addMonths(d, 1)), 'yyyy-MM-dd');
  mutate(['calendar', start, end]);
}

export async function createEvent(eventData, currentDate) {
  const startTime = new Date(eventData.start_time);
  const endTime = new Date(startTime.getTime() + (eventData.duration || 60) * 60000);

  const payload = {
    client: String(eventData.client),
    title: eventData.title || 'Занятие',
    description: eventData.description || '',
    start_time: startTime.toISOString(),
    end_time: endTime.toISOString(),
    price: eventData.price,
    is_recurring: eventData.is_recurring || false,
    ...(eventData.subject && { subject_id: Number(eventData.subject) }),
  };

  const res = await createCalendarLesson(payload);
  revalidateCalendar(currentDate);
  return res;
}

export async function updateEvent(eventData, currentDate) {
  const { id, ...data } = eventData;

  const updatePayload = {};
  if (data.start_time) {
    const startTime = new Date(data.start_time);
    const endTime = new Date(startTime.getTime() + (data.duration || 60) * 60000);
    updatePayload.start_time = startTime.toISOString();
    updatePayload.end_time = endTime.toISOString();
  }
  if (data.price != null) updatePayload.price = data.price;
  if (data.description != null) updatePayload.description = data.description;
  if (data.status) updatePayload.status = data.status;

  const res = await updateCalendarLesson(String(id), updatePayload);
  revalidateCalendar(currentDate);
  return res;
}

export async function deleteEvent(eventId, deleteAllFuture = false, currentDate) {
  await deleteCalendarLesson(String(eventId), deleteAllFuture);
  revalidateCalendar(currentDate);
}
