import React, { useCallback, useEffect, useState } from 'react';
import { formatDate } from '@fullcalendar/core';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { INITIAL_EVENTS, createEventId } from './event-utils';

export default function EventCalendar({removeAfterDrop, eventList, activeCategory}) {
  const [weekendsVisible, setWeekendsVisible] = useState(true);
  const [currentEvents, setCurrentEvents] = useState([]);

  function handleWeekendsToggle() {
    setWeekendsVisible(!weekendsVisible);
  }

  function handleDateSelect(selectInfo) {
    let title = prompt('Please enter a new title for your event');
    // let calendarApi = selectInfo.view.calendar;

    // calendarApi.unselect(); // clear date selection

    if (title) {
    //   calendarApi.addEvent({
    //     id: createEventId(),
    //     title,
    //     start: selectInfo.startStr,
    //     end: selectInfo.endStr,
    //     allDay: selectInfo.allDay,
    //   });
      let newEvent = {
        id: createEventId(),
        title,
        start: selectInfo.startStr,
        end: selectInfo.endStr,
        allDay: selectInfo.allDay,
      }
      setCurrentEvents(prev => ([...prev, newEvent]))
    }
  }

  const onDrop = (event) => {
    // console.log('event', event)
        if(event){
            let newEvent = {
                id: createEventId(),
                title: event.draggedEl.innerText,
                start: event.startStr,
                // end: event.endStr,
                allDay: event.allDay,
                ...event
            }
            setCurrentEvents(prev => ([...prev, newEvent]))
            // if(removeAfterDrop){
            //   setDummyEvents(prev => prev.filter(item => item.title != newEvent.title))
            // }
        }
  }

  const removeEvent = (event) => {
    let eventToRemove = event?.event?._def?.publicId
    let remainingEvent = currentEvents.filter(item => item.id != eventToRemove)
    setCurrentEvents(remainingEvent)
  }


  // function handleEventClick(clickInfo) {
  //   if (
  //     confirm(
  //       `Are you sure you want to delete the event '${clickInfo.event.title}'`
  //     )
  //   ) {
  //     clickInfo.event.remove();
  //   }
  // }

  function handleEvents(events) {
    // setCurrentEvents(events);
  }

  useEffect(()=>{
    // let newEventList = eventList?.map(item => ({...item, start: new Date(item?.start)}))
    let newEventList = eventList?.filter(item => (Number(item.category) == Number(activeCategory)))?.map(item => ({...item, start: new Date(item?.start)}))
    // console.log('newEventList', newEventList)
    setCurrentEvents(newEventList)
  },[activeCategory])

  return (
    <div className="demo-app">
      <div className="demo-app-main">
        <FullCalendar
          plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
          headerToolbar={{
            left: 'prev,next,today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay',
          }}         
          initialView="dayGridMonth"
          editable={true}
          selectable={true}
          selectMirror={true}
          dayMaxEvents={true}
          weekends={weekendsVisible}
        //   initialEvents={INITIAL_EVENTS} // alternatively, use the `events` setting to fetch from a feed
          events={currentEvents}
          eventContent={renderEventContent} // custom render function
          eventsSet={handleEvents} // called after events are initialized/added/changed/removed
          // select={handleDateSelect}
          // eventClick={handleEventClick}
          /* you can update a remote database when these fire:
          eventAdd={function(){}}
          eventChange={function(){}}
          eventRemove={function(){}}
          */

          // eventBackgroundColor='purple'
          // eventRemove={removeEvent}
          droppable= {true} // this allows things to be dropped onto the calendar
          drop={onDrop}
        />
      </div>
    </div>
  );
}

function renderEventContent(eventInfo) {
  return (
    <>
      {/* <b>{eventInfo.timeText}</b> */}
      <i>{eventInfo.event.title}</i>
    </>
  );
}
