import React, { useCallback, useEffect, useState } from "react";
import { useMutation, useQuery } from '@tanstack/react-query'

import BreadcrumbComBS from "../breadcrumb/BreadcrumbComBS";
import EventCalendar from "./EventCalendar";
import ExternalDraggable from "./ExternalDraggable";

import { getCalendarEvents } from '../../services/services'
import queryKeys from '../../services/queryKeys'


export default function Calendar(){

    // const [draggedEvent, setDraggedEvent] = useState('undroppable')
    // const handleDragStart = (event) => {
    //     setDraggedEvent(event)
    // }

    // const {data, isFetching, isError, error} = useQuery({
    //     queryKey: queryKeys.calendar_events,
    //     queryFn: () => getCalendarEvents()
    // })

    // const calendarEvents = useMutation({
    //     mutationFn: (reqData) => {
    //         return getCalendarEvents(reqData)
    //     },
    //     onError: (error) => {
    //         console.log(error)
    //     },
    //     onSuccess: (res) => {
    //         if(res?.data?.resultCode != '0'){
    //             throw({message: 'Something went wrong'})
    //         }
    //     }
    // })

    // useEffect(()=>{
    // let reqData = {
    //     token: localStorage.getItem('token'), // USER TOKEN
    //     uid: localStorage.getItem('uid') // USER UID
    // }
    // calendarEvents.mutate(reqData)
    // },[])
    let reqData = {
        token: localStorage.getItem('token'), // USER TOKEN
        uid: localStorage.getItem('uid') // USER UID
    }
    const {data, isFetching, isError, error} = useQuery({
        queryKey: queryKeys.calendar_events,
        queryFn: () => getCalendarEvents(reqData),
        staleTime: 0
    })

    const receievedEvents = data?.data
    const category = receievedEvents?.category  //EVENT CATEGORIES FROM API
    const eventList = receievedEvents?.list //EVENT LIST FROM API

    const [activeCategory, setActiveCategory] = useState('1')

    const [removeAfterDrop, setRemoveAfterDrop] = useState(false)

    const [newEvent, setNewEvent] = useState({
        title: '', color: ''
    })

    const handleEditEvent = ({target:{name,value}}) => {
        setNewEvent(prev => ({...prev, [name]:value}))
    }

    const handleAddNewEvent = () => {
        if(newEvent.title && newEvent.color){
            const eventToAdd = {...newEvent}
            // setDefaultCategory(prev => ([...prev, eventToAdd]))
            setNewEvent({title: '', color: ''})
        }
    }

    const handleActiveCategory = (id) => {
        setActiveCategory(id)
    }

    return(
        <>
            <BreadcrumbComBS title='Calendar' paths={['Dashboard', 'Calendar']} />
            <div className="row">
                <div className="col-lg-12">
                    <div className="card card-statistics">
                        <div className="card-header">
                            <div className="card-heading">
                                <h4 className="card-title">Events</h4>
                            </div>
                        </div>
                        <div className="card-body">
                            <div className="row">
                            {isFetching ? 
                                <>
                                    <div className="col-12">
                                        <p className='text-mute'>Loading...</p>
                                    </div>
                                </>
                                : isError ?
                                <div className="col-12">
                                    <p className='text-danger'>{error?.message}</p>
                                </div>
                                :
                                <>
                                    <div className="col-xl-3">
                                       
                                        {/* <button className="btn btn-primary btn-block" data-bs-toggle="modal" data-bs-target="#eventModal">
                                            Add New Event
                                        </button>
                                        <p className="mt-3">
                                            Drag and drop your event or click in the calendar.
                                        </p> */}

                                        {category?.map((item, index) => {
                                            let color = item?.cid == '1' ? 'fc-event-success' : item?.cid == '2' ? 'fc-event-danger' : item?.cid == '3' ? 'fc-event-warning' : 'fc-event-primary'
                                            let circleColor = item?.cid == '1' ? 'text-success' : item?.cid == '2' ? 'text-danger' : item?.cid == '3' ? 'text-warning' : 'text-primary'
                                            return (
                                                // <div key={index} className={`fc-event ${color}`} data-color={`${color}`} 
                                                //     // draggable={false}
                                                //     // onDragStart={() =>
                                                //     // handleDragStart({...item})
                                                //     // }
                                                // >
                                                //     <span>{item.description}</span>
                                                // </div>

                                                // <div key={index} className={`form-check ${color}`}>
                                                //     <input className="form-check-input" type="radio" value={item.cid}
                                                //         id={item.cid} name='category' checked={item.cid == activeCategory} onChange={() => handleActiveCategory(item.cid)} />
                                                //         <label className={`w-100 form-check-label`} htmlFor={item.cid}>
                                                //         {item.description}
                                                //         </label>
                                                // </div>

                                                <div key={index} className={`form-check ${color}`} onClick={() => handleActiveCategory(item.cid)} style={{cursor: 'pointer'}}>
                                                    <div>
                                                        <span className="nav align-items-center">
                                                            <span>
                                                                <i className={`fa fa-circle-o pr-4 ${item.cid == activeCategory ? circleColor : 'text-light'}`}></i>
                                                            </span>
                                                        <span>
                                                            <span>{item?.description}</span>
                                                        </span>
                                                        </span>
                                                    </div>
                                                </div>
                                            )
                                        }
                                        )}

                                        {/* <div id="external-events">
                                            <ExternalDraggable category={category} />
                                        </div> */}

                                        {/* <div className="form-check">
                                            <input className="form-check-input" type="checkbox" value={removeAfterDrop}
                                                id="defaultCheck1" onChange={() => setRemoveAfterDrop(prev => !prev)} />
                                                <label className="form-check-label" htmlFor="defaultCheck1">
                                                    Remove After Drop
                                                </label>
                                        </div> */}
                                    </div>
                                    <div className="col-xl-9">
                                        <div className="event-calendar">
                                            <EventCalendar 
                                                removeAfterDrop={removeAfterDrop} 
                                                eventList={eventList}
                                                activeCategory={activeCategory}
                                            />
                                        </div>
                                    </div>
                                </>
                            }
                            </div>

                        </div>
                    </div>
                </div>
            </div>

            {/* Event Modal */}
            <div className="modal fade" id="eventModal" tabIndex="-1" role="dialog">
                <div className="modal-dialog modal-dialog-centered" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title" id="verticalCenterTitle">Add New Event</h5>
                            <button type="button" className="close" data-bs-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div className="modal-body">
                            <form>
                                <div className="form-group">
                                    <label>Event Name</label>
                                    <input type="email" className="form-control" id="eventname" name='title' value={newEvent.title} onChange={handleEditEvent} />
                                </div>
                                <div className="form-group">
                                    <label>Choose Event Color</label>
                                    <select className="form-control" name='color' value={newEvent.color} onChange={handleEditEvent}>
                                        <option value={''}>Select</option>
                                        <option value={'fc-event-primary'}>Primary</option>
                                        <option value={'fc-event-warning'}>Warning</option>
                                        <option value={'fc-event-success'}>Success</option>
                                        <option value={'fc-event-danger'}>Danger</option>
                                    </select>
                                </div>

                            </form>
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Close</button>
                            <button type="button" className="btn btn-success" onClick={handleAddNewEvent}>Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}