import React, { Component } from "react";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { Card, CardBody, CardHeader, CardTitle, Button, Row, Col, FormGroup, Input } from "reactstrap";
import { getPelaporan, getOneLaporan, updateLaporan } 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 Select from "react-select";
import moment from "moment-timezone";
import { connect } from "react-redux";
import Loader from "@/components/Common/Loader";
import Router from "next/router";
import { ToastContainer, toast } from "react-toastify";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import Datetime from "react-datetime";

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" },
];

const jadwalSchema = Yup.object().shape({
	judul: Yup.string().required("Required"),
	dari_tanggal: Yup.date().required("Required"),
	sampai_tanggal: Yup.date().required("Required"),
});

const laporanSchema = Yup.object().shape({
	keterangan: Yup.string().required("Harus diisi"),
});

class Calendar extends Component {
	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,
			color: "",
		};
	}

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

	async componentDidMount() {
		const { token, query } = this.props;
		const laporan = await getOneLaporan(token, query.id);
		const dataLaporan = await getPelaporan(token, { jadwal: true });

		this.setState({ dataLaporan });
		this.getDataEvent();
		this.defaultStatus();
		this.setState({ laporan });

		let color = "#" + Math.random().toString(16).slice(2, 8);
		if (laporan.data.jadwal) {
			color = laporan.data.jadwal.warna;
		}
		this.setState({ color });
	}

	componentShouldUpdate(nextProps, nextState) {
		return nextState.dataLaporan !== this.state.dataLaporan;
	}

	getStatus = () => (this.props.user?.role.id === 2021 ? statusLLDIKTI : status);

	getDataEvent = () => {
		const dataEvent = this.state.dataLaporan.data.map((e) => ({
			id: e._id,
			title: e.jadwal.judul,
			start: moment(e.jadwal.dari_tanggal).format("YYYY-MM-DD"),
			end: moment(e.jadwal.sampai_tanggal).add(1, "d").format("YYYY-MM-DD"),
			backgroundColor: e.jadwal.warna,
			borderColor: e.jadwal.warna,
		}));
		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 });
	};

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

	handleEventCalendar = async (data) => {
		const { query, token } = this.props;
		const { id } = query;
		const { color, laporan } = this.state;

		await toast.promise(
			updateJadwal(token, id, {
				judul: "No.Laporan " + laporan.data.no_laporan + " - " + data.judul,
				dari_tanggal: data.dari_tanggal,
				sampai_tanggal: data.sampai_tanggal,
				warna: color,
			}),
			{
				pending: "Loading",
				success: "Success",
				error: "Error",
			}
		);
		const dataLaporan = await getPelaporan(token, { jadwal: true });
		this.setState({ dataLaporan });
		this.getDataEvent();
	};

	defaultStatus = async () => {
		const status = this.getStatus();
		return this.setState({ selectedOption: status[0] });
	};

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

	handleSimpan = async (value) => {
		const { token, query } = this.props;
		const { id } = query;
		let update = null;
		if (value.status.value === this.getStatus()[1].value || value.status.value === this.getStatus()[2].value) {
			const toastid = toast.loading("Please wait...");
			const data = { keterangan: value.keterangan };
			if (value.status.value === this.getStatus()[1].value) {
				data.change_role = "true";
				update = await updateLaporan(token, id, data);
			} else if (value.status.value === this.getStatus()[2].value) {
				data.aktif = "false";
				update = await updateLaporan(token, id, data);
			}
			if (!update) {
				toast.update(toastid, { render: "All is not good", type: "error", isLoading: false, autoClose: true, closeButton: true });
			} else {
				toast.update(toastid, { render: "All is good", type: "success", isLoading: false, autoClose: true, closeButton: true });
				Router.push("/app/penjadwalan");
			}
		}
	};

	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 data={laporan.data} />
									</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">
										<div class="header-penjadwalan">
											<h2 class="card-title-1">Status Pelaporan</h2>
										</div>
										<CardBody>
											<Formik
												enableReinitialize={true}
												initialValues={{
													status: this.getStatus()[0],
													keterangan: "",
												}}
												validationSchema={selectedOption?.value === this.getStatus()[2].value || selectedOption?.value === this.getStatus()[1].value ? laporanSchema : null}
												onSubmit={this.handleSimpan}
											>
												{() => (
													<Form>
														<FormGroup>
															<label className="col-form-label">Status Laporan</label>
															<Field name="status">
																{({ field, form }) => (
																	<Select
																		value={field.value}
																		onChange={(e) => {
																			form.setFieldValue(field.name, e);
																			this.handleChangeSelect(e);
																		}}
																		options={this.getStatus()}
																		required
																	/>
																)}
															</Field>
															<ErrorMessage name="status" component="div" className="form-text text-danger" />
														</FormGroup>
														{selectedOption?.value === this.getStatus()[0].value ? (
															""
														) : (
															<FormGroup>
																<label className="col-form-label">Keterangan</label>
																<Field name="keterangan">{({ field, form }) => <Input type="text" placeholder="Keterangan" {...field} />}</Field>
																<ErrorMessage name="keterangan" component="div" className="form-text text-danger" />
															</FormGroup>
														)}
														<div className="btn-simpanjadwal">
															<Button className="text-btn-penjadwalan-1 btn-colorpenjadwalan" color="primary" block disabled={laporan.data?.evaluasi.length}>
																<h4 className="text-btn-penjadwalan-1">Simpan</h4>
															</Button>
														</div>
													</Form>
												)}
											</Formik>
										</CardBody>
									</Card>
									{selectedOption?.value === this.getStatus()[2].value || selectedOption?.value === this.getStatus()[1].value ? (
										""
									) : (
										<>
											<Card className="card-default" title="">
												<div class="header-penjadwalan">
													<h2 className="card-title-1">Input Jadwal</h2>
												</div>
												<CardBody>
													<Formik
														enableReinitialize={true}
														initialValues={{
															judul: laporan.data?.jadwal?.judul ? laporan.data.jadwal.judul.split("- ")[1] : "",
															dari_tanggal: laporan.data?.jadwal?.dari_tanggal ? moment(laporan.data.jadwal.dari_tanggal).format("DD MMMM YYYY") : "",
															sampai_tanggal: laporan.data?.jadwal?.sampai_tanggal ? moment(laporan.data.jadwal.sampai_tanggal).format("DD MMMM YYYY") : "",
														}}
														validationSchema={jadwalSchema}
														onSubmit={this.handleEventCalendar}
													>
														{() => (
															<Form>
																<FormGroup>
																	<label className="col-form-label">Warna</label>
																	<div className="badge d-block" style={{ backgroundColor: this.state.color, color: "white" }}>
																		{this.state.color}
																	</div>
																	{/* <div className="warna-penjadwalan-block" style={{ backgroundColor: this.state.color, color: "white" }}></div> */}
																</FormGroup>

																<FormGroup>
																	<label className="col-form-label">Judul</label>
																	<Field name="judul">{({ field, form }) => <Input type="text" placeholder="judul" {...field} />}</Field>
																	<ErrorMessage name="judul" component="div" className="form-text text-danger" />
																</FormGroup>
																<Row>
																	<Col>
																		<FormGroup>
																			<label className="col-form-label">Dari Tanggal</label>
																			<Field name="dari_tanggal">
																				{({ field, form }) => (
																					<Datetime
																						timeFormat={false}
																						inputProps={{ className: "form-control" }}
																						value={field.value}
																						onChange={(e) => {
																							form.setFieldValue(field.name, e.format("DD MMMM YYYY"));
																						}}
																					/>
																				)}
																			</Field>
																			<ErrorMessage name="dari_tanggal" component="div" className="form-text text-danger" />
																		</FormGroup>
																	</Col>
																	<Col>
																		<FormGroup>
																			<label className="col-form-label">Sampai Tanggal</label>
																			<Field name="sampai_tanggal">
																				{({ field, form }) => (
																					<Datetime
																						timeFormat={false}
																						inputProps={{ className: "form-control" }}
																						value={field.value}
																						onChange={(e) => {
																							form.setFieldValue(field.name, e.format("DD MMMM YYYY"));
																						}}
																					/>
																				)}
																			</Field>
																			<ErrorMessage name="sampai_tanggal" component="div" className="form-text text-danger" />
																		</FormGroup>
																	</Col>
																</Row>

																<FormGroup>
																	<div className="btn-simpanpenjadwalan">
																		<Button color="info" className="btn-colorpenjadwalan" block type="submit" disabled={laporan.data?.evaluasi.length}>
																			<h4 className="text-btn-penjadwalan-1">Simpan</h4>
																		</Button>
																	</div>
																</FormGroup>
															</Form>
														)}
													</Formik>
												</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}
										deepChangeDetection={true}
										eventClick={this.eventClick}
									></FullCalendar>
								</CardBody>
							</Card>
						</div>
					</div>
				</div>
			</ContentWrapper>
		);
	}
}

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