import React, { Component } from "react";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { Card, CardBody, CardHeader, CardTitle } from "reactstrap";
import { getPelaporan } from "@/actions/pelaporan";
import { updateJadwal } from "@/actions/penjadwalan";
import DetailLaporan from "@/components/Penjadwalan/DetailLaporan";
import Link from "next/link";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin, { Draggable } from "@fullcalendar/interaction";
import listPlugin from "@fullcalendar/list";
import bootstrapPlugin from "@fullcalendar/bootstrap";
import events from "./calendar.events";

class Calendar extends Component {
	calendarEvents = events;

	calendarPlugins = [interactionPlugin, dayGridPlugin, timeGridPlugin, listPlugin, bootstrapPlugin];

	calendarHeader = {
		left: "prev,next today",
		center: "title",
		right: "dayGridMonth,timeGridWeek,timeGridDay,listWeek",
	};

	constructor(props) {
		super(props);
		this.state = {
			selectedEvent: null,
			evRemoveOnDrop: true,
			evNewName: "",
			externalEvents: [],
			dataLaporan: [],
			dataEvent: [],
			laporan: {},
			selectedOption: null,
		};
	}

	async componentDidMount() {
		/* initialize the external events */
		new Draggable(this.refs.externalEventsList, {
			itemSelector: ".fce-event",
			eventData: function (eventEl) {
				return {
					title: eventEl.innerText.trim(),
				};
			},
		});

		const dataLaporan = await getPelaporan({ penjadwalan: true });
		const { data } = await getPelaporan({ number: this.props.query.number, ptId: this.props.query.ptId });
		this.setState({ dataLaporan });
		this.getDataEvent();

		// const cek = this.state.dataLaporan.data.filter((e) => e._number === this.props.query.number && e.pt_id == this.props.query.ptId)[0];
		this.setState({ laporan: data[0] });
		let color = "#" + Math.floor(Math.random() * 16777215).toString(16);
		if (data[0].penjadwalan) {
			color = data[0].penjadwalan.background_color;
		}
		this.setState({ externalEvents: [{ id: this.props.query.number, color: color, name: "Jadwal Pemeriksaan - BI:" + this.props.query.number }] });
	}

	getDataEvent = () => {
		const dataEvent = this.state.dataLaporan.data
			.filter((e) => e.penjadwalan)
			.map((e) => ({
				title: e.penjadwalan.title,
				start: new Date(e.penjadwalan.from_date),
				end: new Date(e.penjadwalan.to_date),
				backgroundColor: e.penjadwalan.background_color, //red
				borderColor: e.penjadwalan.background_color,
			}));
		this.setState({ dataEvent });
	};

	dayClick = (date) => {
		this.setState({
			selectedEvent: {
				date: date.dateStr,
			},
		});
	};

	addEvent(event) {
		this.calendarEvents.push(event);
	}

	handleEventReceive = (info) => {
		var styles = getComputedStyle(info.draggedEl);
		info.event.setProp("backgroundColor", styles.backgroundColor);
		info.event.setProp("borderColor", styles.borderColor);
		this.handleEventCalendar(info);
	};

	handleEventCalendar = async ({ event }) => {
		const number = this.props.query.number;
		const ptId = this.props.query.ptId;
		const data = {
			title: event.title,
			from_date: event.start,
			to_date: event.end || event.start,
			background_color: event.backgroundColor,
		};

		const update = await updateJadwal({ number, ptId }, data);
	};

	handleChangeSelect = (selectedOption) => {
		this.setState({ selectedOption });
	};

	render() {
		const { externalEvents, laporan, selectedOption } = this.state;
		return (
			<ContentWrapper>
				<div className="content-heading">
					<div>
						Jadwal Pemeriksaan
						<small>Format pembuatan jadwal pemeriksaan v.0.1</small>
					</div>
					<div className="ml-auto">
						<Link href="/app/penjadwalan">
							<button className="btn btn-sm btn-secondary text-sm">&lt; back</button>
						</Link>
					</div>
				</div>
				<div className="calendar-app">
					<div className="row">
						<div className="col-xl-4 col-lg-5">
							<div className="row">
								<div className="col-lg-12 col-md-6 col-12">
									{selectedOption && selectedOption.value === "ditutup" ? (
										""
									) : (
										<Card className="card-default" title="">
											<CardHeader>
												<CardTitle tag="h4">Daftar Pemeriksaan</CardTitle>
											</CardHeader>
											<CardBody>
												<div className="external-events" ref="externalEventsList">
													{externalEvents.map((ev) => (
														<div
															className="fce-event"
															style={{
																backgroundColor: ev.color,
															}}
															key={ev.name + ev.color}
															data-id={ev.id}
														>
															{ev.name}
														</div>
													))}
												</div>
											</CardBody>
										</Card>
									)}
									{laporan ? <DetailLaporan query={this.props.query} data={laporan} handleChangeSelect={this.handleChangeSelect} /> : ""}
								</div>
							</div>
						</div>
						<div className="col-xl-8 col-lg-7">
							<Card className="card-default">
								<CardBody>
									{/* START calendar */}
									<FullCalendar
										defaultView={this.dayGridMonth}
										plugins={this.calendarPlugins}
										events={this.state.dataEvent}
										themeSystem={"bootstrap"}
										header={this.calendarHeader}
										editable={true}
										droppable={true}
										deepChangeDetection={true}
										dateClick={this.dayClick}
										eventReceive={this.handleEventReceive}
										eventDrop={this.handleEventCalendar}
										eventResize={this.handleEventCalendar}
									></FullCalendar>
								</CardBody>
							</Card>
						</div>
					</div>
				</div>
			</ContentWrapper>
		);
	}
}

export default Calendar;
