import React, {useState, useEffect} from "react";
import { useNavigate } from "react-router-dom";
import { AuthService, EventsService, CustomerService, ResourceService, VehicleService, EmployeeService } from "../../services";
import moment from 'moment';
import { Breadcrumb, Tabs, Tab, Button, Modal, Dropdown } from "react-bootstrap";
import { useCalendarApp, ScheduleXCalendar } from '@schedule-x/react';
import {
  viewMonthGrid,
	createViewDay,
	createViewWeek,
	createViewMonthGrid
} from '@schedule-x/calendar';
import { createEventsServicePlugin } from '@schedule-x/events-service';
import { createEventModalPlugin} from '@schedule-x/event-modal';
import { createEventRecurrencePlugin } from "@schedule-x/event-recurrence";
import '@schedule-x/theme-default/dist/calendar.css';
import { Archive, PencilSquare, Filter } from "react-bootstrap-icons";
import DatePicker from "react-datepicker";
import { vehicleSlice } from "../../store";
// import { Scheduler } from "@aldabil/react-scheduler";


const EventsCalendar = () => {
  const navigate = useNavigate();
  const [events, setEvents] = useState([]);
	const [allEvents, setAllEvents] = useState([]);
	const [targetedEventType, setTargetedEventType] = useState('medical');
	const [currentTab, setCurrentTab] = useState('medicalCalendar');
  const [customers, setCustomers] = useState([]);
	const [resources, setResources] = useState([]);
	const [fromDate, setFromDate] = useState(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
  const [toDate, setToDate] = useState(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0));
	const [currentTotalTranslate1, setCurrentTotalTranslate1] = useState(0);
	const [currentTotalTranslate2, setCurrentTotalTranslate2] = useState(0);
	const [currentTotalResource, setCurrentTotalResource] = useState(0);
	const [showDeletedItems, setShowDeletedItems] = useState(false);
	const [timeData, setTimeData] = useState([]);
	const [showFilterDropdown, setShowFilterDropdown] = useState(false);
	const eventsServicePlugin = createEventsServicePlugin();
	const eventModalService = createEventModalPlugin();
	const eventRecurrence = createEventRecurrencePlugin();
	const [groupedEvents, setGroupedEvents] = useState(new Map());
	const [currentView, setCurrentView] = useState('month');
	const [currentViewDate, setCurrentViewDate] = useState(new Date());
	const [showCreationModal, setShowCreationModal] = useState(false);
	const [newEventStartDateTime, setNewEventStartDateTime] = useState(new Date());
	const [newEventEndDateTime, setNewEventEndDateTime] = useState(new Date())
	const [newEventType, setNewEventType] = useState('');
	const [newEventTitle, setNewEventTitle] = useState('');
	const [newEventDescription, setNewEventDescription] = useState('');
	const [newEventLocation, setNewEventLocation] = useState('');
	const [newEventTarget, setNewEventTarget] = useState(undefined);
	const [newEventSource, setNewEventSource] = useState(undefined);
	const [newEventDepartment, setNewEventDepartment] = useState('');
	const [newEventColor, setNewEventColor] = useState('');
	const [newEventSourceType, setNewEventSourceType] = useState('');
	const [newEventTargetType, setNewEventTargetType] = useState('');
	const [newEventFutureDate, setNewEventFutureDate] = useState(undefined);
	const [newEventReminderType, setNewEventReminderType] = useState('');
	const [newEventRecurring, setNewEventRecurring] = useState(undefined);
	const [vehicles, setVehicles] = useState([]);
	const [employees, setEmployees] = useState([]);

	// Helper function to format name from "lastname, firstname" to "firstname lastname"
	const formatFullName = (name) => {
		if (!name) return '';
		if (name.includes(',')) {
			const parts = name.split(',').map(part => part.trim());
			return `${parts[1]} ${parts[0]}`; // firstname lastname
		}
		return name;
	};

	// Helper function to get shortened name
	const getShortenedName = (name) => {
		if (!name) return '';
		const fullName = formatFullName(name);
		const parts = fullName.split(' ');
		if (parts.length >= 2) {
			return `${parts[0]} ${parts[parts.length - 1].charAt(0)}`; // FirstName L
		}
		return fullName;
	};

	// Helper function to format event title
	const formatEventTitle = (customerName, startTime) => {
		const fullName = formatFullName(customerName);
		const timeStr = startTime ? moment(new Date(startTime)).format('hh:mm A') : '';
		
		// Try: "Time: Full Name"
		const titleWithTime = timeStr ? `${timeStr}: ${fullName}` : fullName;
		if (titleWithTime.length <= 35) {
			return fullName;
		}
		
		// Try: "Full Name"
		if (fullName.length <= 35) {
			return fullName;
		}
		
		// Use: "FirstName L"
		return getShortenedName(customerName);
	};

	const eventTypeMap = {
		medicalCalendar: 'medical',
		activitiesCalendar: 'activity',
		incidentsCalendar: 'incident',
		mealPlanCalendar: 'meal_plan',
		reminderDatesCalendar: 'reminder'
	}

	const calendar = useCalendarApp({
		views: [createViewMonthGrid(), createViewDay(), createViewWeek()],
		monthGridOptions: {
			/**
			 * Number of events to display in a day cell before the "+ N events" button is shown
			 * */
			nEventsPerDay: 50,
		},
		defaultView: viewMonthGrid.name,
		skipValidation: true,
		selectedDate: moment(new Date()).format('YYYY-MM-DD HH:mm'),
		events: events,
		plugins: [eventModalService, eventsServicePlugin, eventRecurrence],
		callbacks: {
			onSelectedDateUpdate(date) {
				setCurrentViewDate(new Date(date));
				setFromDate(new Date(new Date(date).getFullYear(), new Date(date).getMonth(), 1)); 
				setToDate(new Date(new Date(date).getFullYear(), new Date(date).getMonth() + 1, 0));
			},
			onViewChange(view) {
				setCurrentView(view);
			},
			onClickDate(date) {
				setNewEventStartDateTime(new Date(date))
				setNewEventEndDateTime(new Date(date));
				setShowCreationModal(true);
			},
			onClickDateTime(dateTime) {
				setNewEventStartDateTime(new Date(dateTime.replace(' ', 'T')));
				setNewEventEndDateTime(new Date(dateTime.replace(' ', 'T')));
				setShowCreationModal(true);
			}
		}
	});

	// Filter events based on current view
	const getFilteredEvents = () => {
		const viewDate = moment(currentViewDate);
		
		// Check for day view
		if (currentView && currentView.toLowerCase().includes('day')) {
			// Show only events for the selected day
			return events.filter(event => {
				const eventDate = moment(event.start_time);
				return eventDate.isSame(viewDate, 'day');
			});
		} 
		// Check for week view
		else if (currentView && currentView.toLowerCase().includes('week')) {
			// Show events for the week containing the selected date
			const startOfWeek = viewDate.clone().startOf('week');
			const endOfWeek = viewDate.clone().endOf('week');
			return events.filter(event => {
				const eventDate = moment(event.start_time);
				return eventDate.isBetween(startOfWeek, endOfWeek, 'day', '[]');
			});
		} 
		// Month view (including month-grid and month-agenda)
		else {
			return events.filter(event => {
				const eventDate = moment(event.start_time);
				return eventDate.isSame(viewDate, 'month');
			});
		}
	};

	const getGroupedEvents = () => {
		const eventsDateMap = new Map();
		const filteredEvents = getFilteredEvents();
		for (const eventItem of filteredEvents) {
			const dateString = moment(eventItem.start_time).format('MMM Do, YYYY');
			if (eventsDateMap.has(dateString)) {
				eventsDateMap.set(dateString, [...eventsDateMap.get(dateString), eventItem]);
			} else {
				const value = [];
				value.push(eventItem);				
				eventsDateMap.set(dateString, value);
			}
		}
		return eventsDateMap;
	};


  useEffect(() => {
    if (!AuthService.canAccessLegacySystem()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change an admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
		VehicleService.getAllActiveVehicles().then((data) => {
			setVehicles(data.data)
		});
		EmployeeService.getAllEmployees().then((data) => {
			setEmployees(data.data);
		});
    CustomerService.getAllCustomers().then((data) => {
      setCustomers(data.data);
    });
		ResourceService.getAll().then((data) => {
			setResources(data.data);
		});
		EventsService.getTimeData().then(data => {
			setTimeData(data.data);
		});
  }, []);

	useEffect(() => {
		EventsService.getAllEvents({ from: EventsService.formatDate(fromDate), to: EventsService.formatDate(toDate) }).then(data => setAllEvents(data?.data));
	}, [fromDate, toDate]);

	useEffect(() => {
		setNewEventType(eventTypeMap[currentTab]);
		if (currentTab === 'medicalCalendar') {
			if (customers?.length > 0 && resources.length > 0) {
				const orignialEvents = [...allEvents];
				setEvents(orignialEvents?.filter(item => item.type === 'medical')?.map((item) => {
					const customerField = item?.data?.customer ? (customers?.find(c => c.id === item?.data?.customer)?.name || item?.data?.client_name || '') : (item?.data?.client_name || '');
					const doctorField = item?.data?.resource ? ((resources?.find(r => r.id === item?.data?.resource))?.name || item?.data?.resource_name || '') : (item?.data?.resource_name || '');
					item.event_id = item.id;
					item.customer = customerField;
					item.doctor = doctorField;
					item.phone = item?.data?.resource ? ((resources?.find(r => r.id === item?.data?.resource))?.phone || item?.data?.resource_phone || '') : (item?.data?.resource_phone || '');
					item.contact = item?.data?.resource? ((resources?.find(r => r.id === item?.data?.resource))?.contact || item?.data?.resource_contact || '') : (item?.data?.resource_contact || '')
					item.address = item?.data?.resource ? ((resources?.find(r => r.id === item?.data?.resource))?.address || item?.data?.resource_address || '') : (item?.data?.resource_address || '');
					item.translation = item?.data?.interpreter || '';
					item.newPatient = item?.data?.new_patient || '';
					item.needId = item?.data?.need_id || '';
					item.disability = item?.data?.disability || '';
					item.startTime = item?.start_time? `${moment(new Date(item?.start_time)).format('YYYY-MM-DD HH:mm')}` : '' ;
					item.endTime = item?.start_time? `${moment(new Date(item?.end_time)).format('YYYY-MM-DD HH:mm')}` : '' ;
					item.fasting = item?.data?.fasting || '';
					item.transportation = item?.link_event_name || '';
					item.title = currentTab==='medicalCalendar' ? formatEventTitle(customerField, item?.start_time) : item.title;
					item.start = item?.start_time? `${moment(new Date(item?.start_time)).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}`;
					item.end = item?.stop_time? `${moment(new Date(item?.stop_time)).format('YYYY-MM-DD HH:mm')}` : (item?.start_time? `${moment(item?.start_time).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}`);
					const transportationInfo = EventsService.getTransportationInfo(allEvents, item, timeData);
					const { isFutureEvent, maxTranslate1, maxTranslate2, maxResource, totalTranslate1, totalTranslate2, totalResource} = transportationInfo;
					item.color = item?.color;
					item._options = { additionalClasses: [`event-${item?.color || 'primary'}`]};
					item.showWarnings = isFutureEvent;
					item.maxTranslate1 = maxTranslate1;
					item.maxTranslate2 = maxTranslate2;
					item.maxResource = maxResource;
					item.totalTranslate1 = totalTranslate1;
					setCurrentTotalTranslate1(item.totalTranslate1);
					item.totalTranslate2 = totalTranslate2;
					setCurrentTotalTranslate2(item.totalTranslate2);
					item.totalResource = totalResource;
					setCurrentTotalResource(item.totalResource);
					return item;
				})?.filter(item => (!showDeletedItems && item.status === 'active') || showDeletedItems));
			}
		} else {
			const originalEvents = [...allEvents];
			setEvents(originalEvents?.filter(item => item.type === eventTypeMap[currentTab])?.map(item => ({
				...item,
				title: item?.title,
				start: item?.start_time? `${moment(new Date(item?.start_time)).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}`,
				end: item?.stop_time? `${moment(new Date(item?.stop_time)).format('YYYY-MM-DD HH:mm')}` : (item?.start_time? `${moment(item?.start_time).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}`),
				_options: { additionalClasses: [`event-${item?.color || 'primary'}`]}
			}))?.filter(item => (!showDeletedItems && item.status === 'active') || showDeletedItems));
		}
	}, [customers, resources, timeData, currentTab, allEvents, showDeletedItems])

	useEffect(() => {	
		if (events && calendar) {
			calendar?.eventsService?.set(events);
			setGroupedEvents(getGroupedEvents());
		}
	}, [events, currentView, currentViewDate]);

	
  const redirectToAdmin = () => {
    navigate(`/medical`)
  }

  const goToEdit = (id) => {
    navigate(`/medical/events/edit/${id}?from=calendar`)
  }

  const goToCreateNew = () => {
    navigate(`/medical/events`)
  }

  const goToList = () => {
		navigate(`/medical/events/list`)
  }

  const goToMultipleList = () => {
		navigate(`/medical/events/multiple-list`)
  }


  const goToView = (id) => {
    navigate(`/medical/events/${id}`)
  }

	const disableEvent = (id) => {
		const currentEvent = events.find(item => item.id === id);
		EventsService.disableEvent(id, { status: 'inactive', edit_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
			edit_date: new Date(),
			edit_history: currentEvent?.edit_history? [...currentEvent.edit_history, { employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }] : [{ employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }]}).then(() => {
			EventsService.getAllEvents({ from: EventsService.formatDate(fromDate), to: EventsService.formatDate(toDate) }).then((data) => {
				setAllEvents(data?.data);
				// if (currentTab === 'medicalCalendar') {
				// 	setEvents(data.data.filter((item) => {
				// 		const customerField = item?.data?.customer ? (customers?.find(c => c.id === item?.data?.customer)?.name || item?.data?.client_name || '') : (item?.data?.client_name || '');
				// 		const doctorField = item?.data?.resource ? ((resources?.find(r => r.id === item?.data?.resource))?.name || item?.data?.resource_name || '') : (item?.data?.resource_name || '');
				// 		item.event_id = item.id;
				// 		item.customer = customerField;
				// 		item.doctor = doctorField;
				// 		item.phone = item?.data?.resource ? ((resources?.find(r => r.id === item?.data?.resource))?.phone || item?.data?.resource_phone || '') : (item?.data?.resource_phone || '');
				// 		item.contact = item?.data?.resource? ((resources?.find(r => r.id === item?.data?.resource))?.contact || item?.data?.resource_contact || '') : (item?.data?.resource_contact || '')
				// 		item.address = item?.data?.resource ? ((resources?.find(r => r.id === item?.data?.resource))?.address || item?.data?.resource_address || '') : (item?.data?.resource_address || '');
				// 		item.translation = item?.data?.interpreter || '';
				// 		item.newPatient = item?.data?.new_patient || '';
				// 		item.needId = item?.data?.need_id || '';
				// 		item.disability = item?.data?.disability || '';
				// 		item.startTime = item?.start_time? `${moment(new Date(item?.start_time)).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}` ;
				// 		item.endTime = item.stop_time? `${moment(new Date(item?.stop_time)).format('YYYY-MM-DD HH:mm')}` : (item?.start_time? `${moment(item?.start_time).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}`);
				// 		item.fasting = item?.data?.fasting || '';
				// 		item.transportation = item?.link_event_name || '';
				// 		item.title = `${customerField}, provider: ${doctorField}`;
				// 		item.start = item?.start_time? `${moment(new Date(item?.start_time)).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}`;
				// 		item.end = item.stop_time? `${moment(new Date(item?.stop_time)).format('YYYY-MM-DD HH:mm')}` : (item?.start_time? `${moment(item?.start_time).format('YYYY-MM-DD HH:mm')}` : `${moment().format('YYYY-MM-DD HH:mm')}`);
				// 		item._options = { additionalClasses: [`event-${item?.color || 'primary'}`]};
				// 		const transportationInfo = EventsService.getTransportationInfo(data.data, item, timeData);
				// 		const { isFutureEvent, maxTranslate1, maxTranslate2, maxResource, totalTranslate1, totalTranslate2, totalResource} = transportationInfo;
				// 		item.color = item?.color;
				// 		item.showWarnings = isFutureEvent;
				// 		item.maxTranslate1 = maxTranslate1;
				// 		item.maxTranslate2 = maxTranslate2;
				// 		item.maxResource = maxResource;
				// 		item.totalTranslate1 = totalTranslate1;
				// 		setCurrentTotalTranslate1(item.totalTranslate1);
				// 		item.totalTranslate2 = totalTranslate2;
				// 		setCurrentTotalTranslate2(item.totalTranslate2);
				// 		item.totalResource = totalResource;
				// 		setCurrentTotalResource(item.totalResource);
				// 		return item;
				// 	}).filter(item => item.type === 'medical'));
				// }
			})
		});
	}

	const FilterAndClose = () => {
    setShowFilterDropdown(false);
  }

	const cleanFilterAndClose = () => {
    setShowFilterDropdown(false);
    setShowDeletedItems(false);
  }

	const goToTab = (value) => {
		setTargetedEventType(eventTypeMap[value]);
		setCurrentTab(value);
	}

	
	const customComponents = {
		eventModal: ({calendarEvent}) => {
			return <>
				
				<div className="sx__event-modal__title">{currentTab === 'medicalCalendar' ? calendarEvent?.customer : calendarEvent?.title}</div>
				{ calendarEvent?.doctor && <div className="sx__event-modal__time">{`${calendarEvent?.doctor}`}</div>}
				<div className="sx__event-modal__time">{`${calendarEvent?.start}`}</div>
				<div className="sx__event-modal__time">
					{currentTab === 'medicalCalendar' && <PencilSquare size={16} onClick={() => goToEdit(calendarEvent?.id)} className="me-4"></PencilSquare>}
					<Archive size={16} onClick={() =>{disableEvent(calendarEvent?.id)}}></Archive> </div>
			</>
		}
	};

	const customMenu = React.forwardRef(
    ({ children, style, className, 'aria-labelledby': labeledBy }, ref) => {
      return (
        <div
          ref={ref}
          style={style}
          className={className}
          aria-labelledby={labeledBy}
        >
          <h6>Filter By</h6>
          <div className="app-main-content-fields-section margin-sm dropdown-container">
            <div className="me-4">
              <div className="field-label">Show Deleted Events</div>
							<input type="checkbox" value={showDeletedItems} checked={showDeletedItems === true} onClick={() => setShowDeletedItems(!showDeletedItems)} />
            </div>
          </div>
          <div className="list row">
            <div className="col-md-12">
              <button className="btn btn-default btn-sm float-right" onClick={() => cleanFilterAndClose()}> Cancel </button>
              <button className="btn btn-primary btn-sm float-right" onClick={() => FilterAndClose()}> Filter </button>
            </div>
          </div>
        </div>
      );
    },
  );

	const calendarView = <div className="multi-columns-container">
		<div className="column-container" style={{'minWidth': '1000px'}}>
			{calendar && <ScheduleXCalendar customComponents={customComponents} calendarApp={calendar} />}
		</div>
		<div className="column-container">
			<div className="column-card" style={{ maxHeight: '800px', overflowY: 'auto', overflowX: 'hidden' }}>
				<h6 className="text-primary me-4">List</h6>
				{
					Array.from(groupedEvents?.keys())?.map((key) => {
						return <div key={key}>
							<h6 className="text-primary me-2">{key}</h6>
							{
								groupedEvents.get(key).map(eventItem => <div 
									key={eventItem.id}
									className={`event-${eventItem.color || 'primary'} mb-4 event-list-item-container`}
									onClick={() => currentTab === 'medicalCalendar' && goToView(eventItem.id)}
									style={{ cursor: currentTab === 'medicalCalendar' ? 'pointer' : 'default' }}
								>
									<div className="event-item-flex">
										<div className="sx__month-agenda-event__title">
											{currentTab === 'medicalCalendar' 
												? `${moment(eventItem?.start_time).format('hh:mm A')}: ${formatFullName(eventItem.customer)}`
												: `${moment(eventItem?.start_time).format('hh:mm A')}: ${eventItem.title}`
											}
										</div>
									</div>
									<div className="sx__event-modal__time with-padding">{ currentTab === 'medicalCalendar' ? `provider: ${eventItem?.doctor}` : eventItem?.description}</div>
									{eventItem?.event_prediction_date && <div className="sx__event-modal__time with-padding">{ `Vehicle: ${eventItem?.target_name}`}</div>}
									{eventItem?.event_prediction_date && <div className="sx__event-modal__time with-padding">{ `Deadline: ${moment(eventItem?.event_prediction_date).format('MM/DD/YYYY')}`}</div>}
								</div>)
							}
						</div>
					})
				}
			</div>
		</div>
	</div>

const handleClose = () => {
	setNewEventDescription('');
	setNewEventTitle('');
	setNewEventLocation('');
	setNewEventSource(undefined);
	setNewEventTarget(undefined);
	setNewEventStartDateTime(undefined);
	setNewEventType('');
	setNewEventFutureDate(undefined);
	setNewEventSourceType('');
	setNewEventTargetType('');
	setShowCreationModal(false);
	setNewEventEndDateTime(undefined);
}
const handleSave = () => {
	const data = {
		title: newEventTitle,
		description: newEventDescription,
		type: newEventType,
		department: newEventDepartment,
		start_time: newEventStartDateTime,
		stop_time: newEventStartDateTime,
		color: newEventColor,
		source_type: newEventSourceType,
		source_uuid: newEventSource?.value,
		source_name: newEventSource?.label,
		target_type: newEventTargetType,
		target_uuid: newEventTarget?.value,
		target_name: newEventTarget?.label,
		event_location: newEventLocation,
		event_prediction_date: newEventFutureDate && moment(newEventFutureDate).format('MM/DD/YYYY'),
		event_reminder_type: newEventReminderType,
		rrule: newEventRecurring,
		status: 'active',
		create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
		edit_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
		edit_date: new Date(),
		create_date: new Date(),
		edit_history: [{ employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }]
	}
	EventsService.createNewEvent(data).then(() => {
		EventsService.getAllEvents({ from: EventsService.formatDate(fromDate), to: EventsService.formatDate(toDate) }).then((data) => {
			setAllEvents(data.data);
			setShowCreationModal(false);
			setNewEventDescription('');
			setNewEventTitle('');
			setNewEventLocation('');
			setNewEventSource(undefined);
			setNewEventTarget(undefined);
			setNewEventStartDateTime(undefined);
			setNewEventType('');
		})
	});
}
  
  
  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/">General</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Calendar
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>
            	Calendar
           </h4> 
        </div>
      </div>

			<div className="app-main-content-list-container" style={{"min-width": "1500px"}}>
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="medicalCalendar" id="medical-calendar-tab" onSelect={(k) => goToTab(k)}>
						<Tab eventKey="medicalCalendar" title="Medical Appointments">
							
						</Tab>
						<Tab eventKey="activitiesCalendar" title="Activities">

						</Tab>
						<Tab eventKey="incidentsCalendar" title="Important Notes And Incidents">
						
						</Tab>
						<Tab eventKey="mealPlanCalendar" title="Meal Plan">
							
						</Tab>
						<Tab eventKey="reminderDatesCalendar" title="Important Dates">
							
						</Tab>
					</Tabs>
					{ calendarView}
					<div className="list-func-panel">
						<Dropdown
							key={'event-calendar-filter'}
							id="event-calendar-filter"
							show={showFilterDropdown}
							onToggle={() => setShowFilterDropdown(!showFilterDropdown)}
							autoClose={false}
						> 
							<Dropdown.Toggle variant="primary">
								<Filter size={16} className="me-2"></Filter>Filter
							</Dropdown.Toggle>
							<Dropdown.Menu as={customMenu}/> 
						</Dropdown>
					</div>
					<Modal show={showCreationModal && currentTab !== 'medicalCalendar'} onHide={handleClose}>
						<Modal.Header closeButton>
							<Modal.Title>Create New Calendar Item</Modal.Title>
						</Modal.Header>
						<Modal.Body>
							<div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Title
										<span className="required">*</span>
									</div>
									<input type="text" placeholder="Briefly Describe activity, incident, menu or reminder" value={newEventTitle || ''} onChange={e => setNewEventTitle(e.target.value)}/>
								</div>
							</div>
							<div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Description
										<span className="required">*</span>
									</div>
									<textarea type="text" placeholder="Details for activity, incident, menu item and ingredients or reminder," value={newEventDescription || ''} onChange={e => setNewEventDescription(e.target.value)}/>
								</div>
							</div>
							<div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Type
										<span className="required">*</span>
									</div>
									<div className="field-value">{newEventType}</div>
								</div>
							</div>
							<div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Want event to be recurring?
										<select value={newEventRecurring} onChange={(e) => setNewEventRecurring(e.target.value)}>
											<option value=""></option>
											<option value="FREQ=YEARLY">Yearly</option>
											<option value="FREQ=MONTHLY">Monthly</option>
											<option value="FREQ=WEEKLY">Weekly</option>
											<option value="FREQ=DAILY">Daily</option>
										</select>
									</div>
								
								</div>
							</div>
							<div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Start Time
										<span className="required">*</span>
									</div>
									<DatePicker
										selected={newEventStartDateTime}
										onChange={setNewEventStartDateTime}
										showTimeInput
										timeInputLabel="Time:"
										dateFormat="MM/dd/yyyy, HH:mm"
									></DatePicker>
								</div>
								<div className="me-4">
									<div className="field-label">End Time 
										<span className="required">*</span>
										<span className="field-blurb float-right">Make sure end time is later than start time </span>
									</div>
									<DatePicker
										selected={newEventEndDateTime}
										onChange={setNewEventEndDateTime}
										showTimeInput
										timeInputLabel="Time:"
										dateFormat="MM/dd/yyyy, HH:mm"
									></DatePicker>
								</div>
							</div>
							{ currentTab !== 'mealPlanCalendar' && <> <div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Who will we take care of in this event:</div>
									<select value={newEventTargetType} onChange={(e) => setNewEventTargetType(e.target.value)}>
										<option value=""></option>
										<option value="vehicle">Vehicle</option>
										<option value="customer">Customer</option>
										<option value="employee">Employee</option>
										<option value="notApplicable">Not Applicable</option>
									</select>
								</div>
								{newEventTargetType && newEventTargetType !== '' && newEventTargetType !== 'notApplicable' && <div className="me-4">
									<div className="field-label">Please select a candidate</div>
									<select value={newEventTarget?.value || ''} onChange={(e) => {
										const selectedOption = e.target.options[e.target.selectedIndex];
										setNewEventTarget({
											value: selectedOption.value,
											label: selectedOption.text
										})
									}}>
										<option value=""></option>
										{
											newEventTargetType === 'vehicle' && vehicles.map((item) => <option value={item?.id}>{item?.vehicle_number}</option>)
										}
										{
											newEventTargetType === 'customer' && customers.map((item) => <option value={item?.id}>{item?.name}</option>)
										}
										{
											newEventTargetType === 'employee' && employees.map((item) => <option value={item?.id}>{item?.name}</option>)
										}
										
									</select>
								</div>}
							</div>

							<div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Who will be responsible for this event</div>
									<select value={newEventSourceType} onChange={(e) => setNewEventSourceType(e.target.value)}>
										<option value=""></option>
										<option value="employee">Employee</option>
										<option value="resource">Resource</option>
										<option value="notApplicable">Not Applicable</option>
									</select>
								</div>
								{newEventSourceType && newEventSourceType !== '' && newEventSourceType !== 'notApplicable' && <div className="me-4">
									<div className="field-label">Please select a member</div>
									<select value={newEventSource?.value || ''} onChange={(e) => {
										const selectedOption = e.target.options[e.target.selectedIndex];
										setNewEventSource({
											value: selectedOption.value,
											label: selectedOption.text
										})
									}}>
										<option value=""></option>
										{
											newEventSourceType === 'resource' && resources.map((item) => <option value={item?.id}>{item?.name}</option>)
										}
										{
											newEventSourceType === 'employee' && employees.map((item) => <option value={item?.id}>{item?.name}</option>)
										}
										
									</select>
								</div>}
							</div> </>}
							<div className="app-main-content-fields-section">
								{currentTab === 'reminderDatesCalendar' && <div className="me-4">
									<div className="field-label">Reminder Type
									</div>
									<select value={newEventReminderType} onChange={(e) => setNewEventReminderType(e.target.value)}>
										<option value=""></option>
										<option value="birthday">Birthday</option>
										<option value="membership">Membership Renew</option>
										<option value="payment">Customer Payment Due Date</option>
										<option value="insurance_renew">Customer Insurance Renew</option>
										<option value="insurance_expire">Vehicle Insurance Renew</option>
										<option value="title_expire">Vehicle Title Registration</option>
										<option value="emission_test">Vehicle Emission Test</option>
										<option value="oil_change">Vehicle Oil Change</option>
									</select>
								</div>}
								{currentTab === 'activitiesCalendar' && <div className="me-4">
									<div className="field-label">Event Location
									</div>
									<input type="text" placeholder="Type in the location this event gonna happen if applicable" value={newEventLocation || ''} onChange={e => setNewEventLocation(e.target.value)}/>
								</div>}
								{currentTab === 'reminderDatesCalendar' && <div className="me-4">
									<div className="field-label">If this is reminder which will happen later, please select the accurate Date it gonna happen:
									</div>
									<DatePicker selected={newEventFutureDate}
										onChange={setNewEventFutureDate} dateFormat="MM/dd/yyyy"/>
								</div>}
								
							</div>
							<div className="app-main-content-fields-section">
								<div className="me-4">
									<div className="field-label">Color
									</div>
									<select value={newEventColor} onChange={e => setNewEventColor(e.target.value)}>
										<option value=""></option>
										{
											EventsService.colorOptions?.map((item) => <option value={item?.value}>{item?.label}</option>)
										}
									</select>
								</div>
							</div>
						</Modal.Body>
						<Modal.Footer>
							<Button variant="secondary" onClick={handleClose}>
								Close
							</Button>
							<Button variant="primary" onClick={handleSave}>
								Save Calendar Item
							</Button>
						</Modal.Footer>
					</Modal>
				</div>
			</div>
    </>
  )
};

export default EventsCalendar;