import React, { Component } from "react";
import { insertPemeriksaan } from "@/actions/pemeriksaan";
import Router from "next/router";
import Datetime from "react-datetime";
import moment from "moment";
import { Row, Col, FormGroup, Input, Button } from "reactstrap";
import { ToastContainer, toast } from "react-toastify";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { getOneLaporan, updateLaporan } from "@/actions/pelaporan";
import { connect } from "react-redux";

const selectInstanceId = 1;
const checkIfFilesAreTooBig = (files) => {
	let valid = true;
	if (files) {
		files.map((file) => {
			if (file.size > 15 * 1024 * 1024) {
				valid = false;
			}
		});
	}
	return valid;
};

const checkIfFilesAreCorrectType = (files) => {
	let valid = true;
	if (files) {
		files.map((file) => {
			if (!["image/jpeg", "image/png"].includes(file.type)) {
				valid = false;
			}
		});
	}
	return valid;
};

const evaluasiSchema = Yup.object().shape({
	tanggal: Yup.date().required("Wajib diisi"),
	judul: Yup.string().min(3).max(150).required("Wajib diisi"),
	dokumen: Yup.array().min(1).required("Wajib diisi").test("filesize", "Maksimal ukuran dokumen 15mb", checkIfFilesAreTooBig),
});

let Dropzone = null;

class DropzoneWrapper extends Component {
	state = {
		isClient: false,
	};
	componentDidMount = () => {
		Dropzone = require("react-dropzone").default;
		this.setState({ isClient: true });
	};
	render() {
		return Dropzone ? <Dropzone {...this.props}>{this.props.children}</Dropzone> : null;
	}
}

class InputEvaluasi extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dropdownOpen: false,
			splitButtonOpen: false,
			judulEvaluasi: "",
			tanggal: moment().format("D MMMM YYYY"),
			files: [],
			delegasichecklist: false,
			rolelldikti: false,
		};
	}

	setjudulEvaluasi = (e) => {
		this.setState({ judulEvaluasi: e.target.value });
	};

	setTanggal = (moment) => {
		this.setState({ tanggal: moment.format("D MMMM YYYY") });
	};

	toggleSplit = () => {
		this.setState({
			splitButtonOpen: !this.state.splitButtonOpen,
		});
	};

	toggleDropDown = () => {
		this.setState({
			dropdownOpen: !this.state.dropdownOpen,
		});
	};

	onDrop = (files) => {
		this.setState({
			files: files.map((file) =>
				Object.assign(file, {
					preview: URL.createObjectURL(file),
				})
			),
			stat: "Added " + files.length + " file(s)",
		});
	};

	uploadFiles = (e) => {
		e.preventDefault();
		e.stopPropagation();
		this.setState({
			stat: this.state.files.length ? "Dropzone ready to upload " + this.state.files.length + " file(s)" : "No files added.",
		});
	};

	clearFiles = (e) => {
		e.preventDefault();
		e.stopPropagation();
		this.setState({
			stat: this.state.files.length ? this.state.files.length + " file(s) cleared." : "No files to clear.",
		});
		this.setState({
			files: [],
		});
	};

	onSubmit = async (data, { resetForm }) => {
		const { token, query } = this.props;
		const { id } = query;
		const formdata = new FormData();
		formdata.append("judul", data.judul);
		formdata.append("tanggal", data.tanggal);
		data.dokumen.forEach((e) => {
			formdata.append("dokumen", e);
		});
		if (this.state.delegasichecklist == true) {
			await toast.promise(insertPemeriksaan(token, id, formdata), {
				pending: "Loading",
				success: "Success",
				error: "Error",

			});

			data.change_role = "true";
			data.keterangan = "delegasi ke DIKTI"
			Router.push("/app/pemeriksaan");
			update = await updateLaporan(token, id, data);
		} else {
			await toast.promise(insertPemeriksaan(token, id, formdata), {
				pending: "Loading",
				success: "Success",
				error: "Error",
			});
		}
		this.setState({ files: [] });
		resetForm();
		const pelaporan = await getOneLaporan(token, query.id);
		this.props.changePelaporan(pelaporan);
	};

	handlechecklist = () => {
		this.setState({ delegasichecklist: !this.state.delegasichecklist })
	};
	// getStatus = () => (this.props.user?.role.id == 2021 ? this.setState({ rolelldikti: !this.state.rolelldikti }) : "")


	render() {
		const { files } = this.state;

		const thumbs = files.map((file, index) => (
			<div md={3} key={index}>
				{/* <img className="img-fluid mb-2" src={file.preview} alt="Item" /> */}
				<span className="text-left">{index + 1}.{file.name}</span>
			</div>
		));
		return (
			<>
				<p className="lead bb">Evaluasi</p>
				<Formik
					initialValues={{
						tanggal: new Date(),
						judul: "",
						dokumen: [],
					}}
					validationSchema={evaluasiSchema}
					onSubmit={this.onSubmit}
				>
					<Form className="form-horizontal">
						<FormGroup row>
							<label className="col-md-2 col-form-label">Tanggal Dokumen</label>
							<div className="col-md-10">
								<Field name="tanggal">
									{({ field, form }) => (
										<Datetime
											timeFormat={false}
											inputProps={{ className: "form-control" }}
											value={field.value}
											onChange={(e) => {
												form.setFieldValue(field.name, e);
											}}
										/>
									)}
								</Field>
								<ErrorMessage name="tanggal" component="div" className="form-text text-danger" />
							</div>
						</FormGroup>
						<FormGroup row>
							<label className="col-md-2 col-form-label">Judul Dokumen</label>
							<div className="col-md-10">
								<Field name="judul">{({ field, form }) => <Input type="text" placeholder="judul" {...field} />}</Field>
								<ErrorMessage name="judul" component="div" className="form-text text-danger" />
							</div>
						</FormGroup>
						<FormGroup row>
							<label className="col-md-2 col-form-label">Upload File Pendukung<span className="text-danger">*</span></label>
							<div className="col-md-10">
								<Field name="dokumen">
									{({ field, form, meta }) => (
										<DropzoneWrapper
											className=""
											onDrop={(e) => {
												this.onDrop(e);
												form.setFieldValue(field.name, e);
											}}
										>
											{({ getRootProps, getInputProps, isDragActive }) => {
												return (
													<div {...getRootProps()} className={"dropzone card" + (isDragActive ? "dropzone-drag-active" : "")}>
														<input name="dokumen" {...getInputProps()} />
														<div className="dropzone-style-1">
															<div className="center-ver-hor dropzone-previews flex">{this.state.files.length > 0 ? <Row><span className="text-left">{thumbs}</span></Row> :
																<div className="text-center fa-2x icon-cloud-upload mr-2 ">
																	<h5 className="text-center dz-default dz-message">Klik untuk upload dokumen</h5>
																</div>
															}
															</div>
														</div>
														<div className="d-flex align-items-center">
															<small className="ml-auto">
																<button
																	type="button"
																	className="btn btn-link"
																	onClick={(e) => {
																		this.clearFiles(e);
																		form.setFieldValue(field.name, []);
																	}}
																>
																	Reset dokumen
																</button>
															</small>
														</div>
													</div>
												);
											}}
										</DropzoneWrapper>
									)}
								</Field>
								<ErrorMessage name="dokumen" component="div" className="form-text text-danger" />
								<p className="mrgn-top-5">
									Ukuran setiap dokumen maksimal 15mb
								</p>
							</div>
						</FormGroup>
						{this.props.user?.role.id === 2021 ? (
							<FormGroup row>
								<label className="col-md-2 col-form-label">Delegasi ke dikti</label>
								<div className="col-md-10 mt-2">
									<div className="checkbox c-checkbox">
										<label>
											<Input type="checkbox" onChange={this.handlechecklist} defaultChecked={this.state.delegasichecklist} />
											<span className="fa fa-check"></span></label>
									</div>
								</div>
							</FormGroup>
						) : ("")}
						<FormGroup row>
							<div className="col-xl-10">
								<Button color className="btn-login" type="submit">
									<span className="font-color-white">
										Simpan Evaluasi
									</span>
								</Button>
							</div>
						</FormGroup>
					</Form>
				</Formik>
			</>
		);
	}
}

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