import React, { Component } from "react";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { Card, CardBody, CardHeader, CardTitle, Button, Row, Col } from "reactstrap";
import { getPelaporan, addStatus, removeLaporan, activeLaporan, changeRoleData } from "@/actions/pelaporan";
import { updateJadwal } from "@/actions/penjadwalan";
import DetailLaporan from "@/components/Main/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";
import Select from "react-select";
import moment from "moment";
import { connect } from "react-redux";
import Loader from "@/components/Common/Loader";

const status = [
	{ value: "Ditindaklanjuti DIKTI", label: "Ditindaklanjuti DIKTI", className: "State-ACT" },
	{ value: "Delegasi ke LLDIKTI", label: "Delegasi ke LLDIKTI", className: "State-ACT" },
	{ value: "Ditutup", label: "Ditutup", className: "State-ACT" },
];

const statusLLDIKTI = [
	{ value: "Ditindaklanjuti LLDIKTI", label: "Ditindaklanjuti LLDIKTI", className: "State-ACT" },
	{ value: "Delegasi ke DIKTI", label: "Delegasi ke DIKTI", className: "State-ACT" },
	{ value: "Ditutup", label: "Ditutup", className: "State-ACT" },
];
class Calendar extends Component {
	calendarEvents = events;

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

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

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

	static getInitialProps = ({ query }) => ({ query });

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

		const { organisasi, peran } = this.props.user.peran[0];

		const queryDataLaporan = { role: peran.id === 2021 ? "lldikti" : "dikti", penjadwalan: true, active: true };
		if (peran.id === 2021) queryDataLaporan.orgId = organisasi.id;
		const dataLaporan = await getPelaporan(queryDataLaporan);

		const laporan = await getPelaporan({ number: this.props.query.number, ptId: this.props.query.ptId });

		this.setState({ dataLaporan });
		this.getDataEvent();
		await this.defaultStatus(laporan.data[0]);
		// 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 });
		let color = "#" + Math.floor(Math.random() * 16777215).toString(16);
		if (laporan.data[0].penjadwalan) {
			color = laporan.data[0].penjadwalan.background_color;
		}
		this.setState({ externalEvents: [{ id: this.props.query.number, color, name: `Jadwal Pemeriksaan - No.Laporan : ${this.props.query.number} - ${laporan.data[0].pt.nama}`, allDay: true }] });
	}

	getStatus = () => (this.props.user.peran[0].peran.id === 2021 ? statusLLDIKTI : status);

	getDataEvent = () => {
		const dataEvent = this.state.dataLaporan.data
			.filter((e) => e.penjadwalan)
			.map((e) => ({
				id: e._id,
				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 });
	};

	eventClick = (info) => {
		const data = {
			title: info.event.title,
			start: moment(info.event.start).format("DD MMMM YYYY"),
			end: moment(info.event.end - 1).format("DD MMMM YYYY"),
		};
		this.setState({ selectedEvent: data });
	};

	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);
	};

	defaultStatus = async (data) => {
		const { ptId, number } = this.props.query;
		const status = this.getStatus();
		if (!data.status) {
			await addStatus({ number, ptId }, { status: status[0].value });
			return this.setState({ selectedOption: status[0] });
		}
		return this.setState({ selectedOption: status.filter((e) => e.value === data.status)[0] });
	};

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

	handleSimpan = async (e) => {
		const { selectedOption } = this.state;
		const { ptId, number } = this.props.query;
		this.setState({ selectedOption });
		if (selectedOption.value === this.getStatus()[1].value) {
			const roleId = this.props.user.peran[0].peran.id;
			await changeRoleData({ number, ptId }, { role_data: roleId === 2021 ? "dikti" : "lldikti" });
			const statusData = roleId === 2021 ? status : statusLLDIKTI;
			await addStatus({ number, ptId }, { status: statusData[0].value });
			return;
		}
		if (selectedOption.value === this.getStatus()[2].value) {
			await removeLaporan({ number, ptId });
		} else if (!this.state.laporan.data[0].active) {
			await activeLaporan({ number, ptId });
		}
		await addStatus({ number, ptId }, { status: selectedOption.value });
	};

	render() {
		const { externalEvents, laporan, selectedOption, selectedEvent } = this.state;
		return (
			<ContentWrapper>
				<div className="content-heading">
					<div>Jadwal Pemeriksaan</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">
					{laporan.data ? (
						<Row>
							<Col>
								<Card className="card-default">
									<CardBody>
										<DetailLaporan noStatus query={this.props.query} data={laporan.data[0]} handleChangeSelect={this.handleChangeSelect} />
									</CardBody>
								</Card>
							</Col>
						</Row>
					) : (
						<Row className="mb-4">
							<Col>
								<Loader />
							</Col>
						</Row>
					)}
					<div className="row">
						<div className="col-xl-4 col-lg-5">
							<div className="row">
								<div className="col-lg-12 col-md-6 col-12">
									<Card className="card-default">
										<CardHeader>
											<CardTitle tag="h4">Status Pelaporan</CardTitle>
										</CardHeader>
										<CardBody>
											<Select value={selectedOption} onChange={this.handleChangeSelect} options={this.getStatus()} required />
											<Button onClick={this.handleSimpan} className="mt-2" color="primary" block>
												Simpan
											</Button>
										</CardBody>
									</Card>
									{selectedOption?.value === this.getStatus()[2].value || selectedOption?.value === this.getStatus()[1].value ? (
										""
									) : (
										<>
											<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.data && laporan.data[0].penjadwalan && (
												<Card className="card-default">
													<CardHeader>
														<CardTitle tag="h4">Jadwal Pemeriksaan</CardTitle>
													</CardHeader>
													<CardBody>
														<table className="table">
															<tbody>
																<tr>
																	<td>Judul</td>
																	<td>{laporan.data[0].penjadwalan.title}</td>
																</tr>
																<tr>
																	<td>Waktu</td>
																	<td>{`${moment(laporan.data[0].penjadwalan.from_date).format("DD MMMM YYYY")} ${
																		moment(laporan.data[0].penjadwalan.from_date).format("DD MMMM YYYY") === moment(laporan.data[0].penjadwalan.to_date).format("DD MMMM YYYY")
																			? ""
																			: `- ${moment(laporan.data[0].penjadwalan.to_date).add(-1, "d").format("DD MMMM YYYY")}`
																	}`}</td>
																</tr>
															</tbody>
														</table>
													</CardBody>
												</Card>
											)}
										</>
									)}
									<div className="mb-3">
										{selectedEvent && (
											<div>
												<p>Selected:</p>
												<div className="box-placeholder">{JSON.stringify(selectedEvent)}</div>
											</div>
										)}
										{!selectedEvent && (
											<div>
												<p>Click calendar to show information</p>
											</div>
										)}
									</div>
								</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}
										eventClick={this.eventClick}
										eventReceive={this.handleEventReceive}
										eventDrop={this.handleEventCalendar}
										eventResize={this.handleEventCalendar}
									></FullCalendar>
								</CardBody>
							</Card>
						</div>
					</div>
				</div>
			</ContentWrapper>
		);
	}
}

const mapStateToProps = (state) => ({ user: state.user });
export default connect(mapStateToProps)(Calendar);
