'use client';

import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import timelinePlugin from '@fullcalendar/timeline';
import ruLocale from '@fullcalendar/core/locales/ru';

import { useState, useEffect, useCallback } from 'react';

import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';

import { paths } from 'src/routes/paths';
import { useAuthContext } from 'src/auth/hooks';
import { useBoolean } from 'src/hooks/use-boolean';
import { useGetEvents, updateEvent, createEvent, deleteEvent } from 'src/actions/calendar';

import { Iconify } from 'src/components/iconify';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { useSettingsContext } from 'src/components/settings';

import { CalendarForm } from '../calendar-form';
import { StyledCalendar } from '../styles';
import { CalendarToolbar } from '../calendar-toolbar';
import { useCalendar } from '../hooks/use-calendar';

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

export function CalendarView() {
  const settings = useSettingsContext();
  const { user } = useAuthContext();
  const isMentor = user?.role === 'mentor';

  const { calendarRef, view, date, onDatePrev, onDateNext, onDateToday, onChangeView,
    onSelectRange, onClickEvent, onResizeEvent, onDropEvent, onInitialView,
    openForm, onOpenForm, onCloseForm, selectEventId, selectedRange } = useCalendar();

  const { events, eventsLoading } = useGetEvents(date);

  useEffect(() => {
    onInitialView();
  }, [onInitialView]);

  const handleCreateEvent = useCallback(
    (eventData) => createEvent(eventData, date),
    [date]
  );

  const handleUpdateEvent = useCallback(
    (eventData) => updateEvent(eventData, date),
    [date]
  );

  const handleDeleteEvent = useCallback(
    (eventId, deleteAllFuture) => deleteEvent(eventId, deleteAllFuture, date),
    [date]
  );

  return (
    <>
      <Container maxWidth={settings.themeStretch ? false : 'xl'}>
        <Stack
          direction="row"
          alignItems="center"
          justifyContent="space-between"
          sx={{ mb: { xs: 3, md: 5 } }}
        >
          <Stack spacing={1}>
            <Typography variant="h4">Расписание</Typography>
            <CustomBreadcrumbs
              links={[
                { name: 'Дашборд', href: paths.dashboard.root },
                { name: 'Расписание' },
              ]}
            />
          </Stack>

          {isMentor && (
            <Button
              variant="contained"
              startIcon={<Iconify icon="mingcute:add-line" />}
              onClick={() => onOpenForm()}
            >
              Новое занятие
            </Button>
          )}
        </Stack>

        <Card sx={{ position: 'relative' }}>
          <StyledCalendar>
            <CalendarToolbar
              date={date}
              view={view}
              loading={eventsLoading}
              onNextDate={onDateNext}
              onPrevDate={onDatePrev}
              onToday={onDateToday}
              onChangeView={onChangeView}
            />

            <FullCalendar
              weekends
              editable={isMentor}
              droppable={isMentor}
              selectable={isMentor}
              rerenderEvents
              events={events}
              ref={calendarRef}
              initialDate={date}
              initialView={view}
              dayMaxEventRows={3}
              eventDisplay="block"
              headerToolbar={false}
              allDayMaintainDuration
              eventResizableFromStart
              displayEventTime={false}
              select={isMentor ? onSelectRange : undefined}
              eventClick={onClickEvent}
              eventDrop={isMentor ? onDropEvent : undefined}
              eventResize={isMentor ? onResizeEvent : undefined}
              plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin, timelinePlugin]}
              locale={ruLocale}
              slotLabelFormat={{ hour: '2-digit', minute: '2-digit', hour12: false }}
              eventTimeFormat={{ hour: '2-digit', minute: '2-digit', hour12: false }}
            />
          </StyledCalendar>
        </Card>
      </Container>

      {isMentor && (
        <CalendarForm
          currentEvent={events.find((event) => event.id === selectEventId)}
          range={selectedRange}
          open={openForm}
          onClose={onCloseForm}
          onCreateEvent={handleCreateEvent}
          onUpdateEvent={handleUpdateEvent}
          onDeleteEvent={handleDeleteEvent}
        />
      )}
    </>
  );
}
