import React, { Component } from "react";
import Router from "next/router";
import Link from "next/link";
import Select from "react-select";
import DetailSanksi from "@/components/Main/DetailSanksi";
import Header from "@/components/Main/Header";
import DetailPT from "@/components/Main/DetailPT";
import PermohonanPT from "@/components/Main/PermohonanPT";
import Riwayat from "@/components/Banding/Riwayat";
import { getOneSanksi } from "@/actions/sanksi";
import { addJawabanBanding } from "@/actions/banding";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { Row, Col, Card, CardBody, FormGroup, Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
import { getPT } from "@/actions/PT";
import Loader from "@/components/Common/Loader";
import { toast } from "react-toastify";
import { connect } from "react-redux";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { createLog } from "@/actions/log";

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

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 jawabanBandingSchema = Yup.object().shape({
	status: Yup.string().required("Harap Diisi"),
	dokumen: Yup.array().min(1, "Minimal terdapat 1 dokumen").required("Required").test("filesize", "Maksimal ukuran dokumen 15mb", checkIfFilesAreTooBig),
});
class JawabanBanding extends Component {
	constructor(props) {
		super(props);
		this.state = {
			modal: false,
			selectedOption: null,
			files: [],
			sanksi: {},
			pt: null,
		};
	}

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

	componentDidMount = async () => {
		const { query, token } = this.props;
		const sanksi = await getOneSanksi(token, query.id, { banding: true });
		await createLog(token, { aktivitas: `Mengakses halaman detail Banding dengan No. Sanksi ${sanksi.data.no_sanksi}`, menu: "Banding" });
		const pt = sanksi.data.laporan.pt;
		this.setState({ sanksi, pt });
	};

	toggleModal = () => {
		this.setState({
			modal: !this.state.modal,
		});
	};

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

	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: [],
		});
	};

	handelSimpan = async () => {
		if (this.state.modal === true) {
			this.toggleModal();
		}
		const { data } = this.state;
		const { query, token } = this.props;
		const { id } = query;
		const formdata = new FormData();
		formdata.append("status", data.status);
		data.dokumen.forEach((e) => {
			formdata.append("dokumen", e);
		});
		const toastid = toast.loading("Please wait...");
		const added = await addJawabanBanding(token, id, formdata);
		if (!added) {
			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({
				pathname: "/app/banding",
			});
		}
	};

	render() {
		const { files, sanksi, pt } = 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 (
			<ContentWrapper unwrap>
				{/* <Header /> */}
				<div className="p-3">
					<div className="content-heading">
						<span className="font-color-white">Jawaban Permohonan Banding</span>
						<div className="ml-auto">
							<Link href="/app/banding">
								<Button className="color-3e3a8e btn-login" color>
									<span className="font-color-white">&lt; Kembali</span>
								</Button>
							</Link>
						</div>
					</div>
					<Row>
						{sanksi.data ? (
							<Col xl={9}>
								<Card className="card-default">
									<CardBody>
										<Row>
											<Col lg={12}>
												<DetailSanksi data={sanksi.data} />
												<PermohonanPT data={sanksi.data.pengajuan.banding} title="Permohonan Banding" />
												<p className="lead bb">Jawaban</p>
												<Formik
													initialValues={{
														status: "",
														dokumen: [],
													}}
													validationSchema={jawabanBandingSchema}
													onSubmit={async (data) => {
														this.setState({ data });
														if (sanksi.data.jawaban?.banding) this.toggleModal();
														else await this.handelSimpan();
													}}
												>
													{() => (
														<Form className="form-horizontal">
															<FormGroup>
																<label className="row-form-label">Status:</label>
																<div className="row-md-10">
																	<Field name="status">
																		{({ field, form, meta }) => (
																			<Select
																				instanceId={selectInstanceId + 1}
																				value={this.state.selectedOption}
																				onChange={(e) => {
																					this.handleChangeSelect(e);
																					form.setFieldValue(field.name, e.value);
																				}}
																				options={[
																					{ value: "Ditolak", label: "Ditolak", className: "State-ACT" },
																					{ value: "Dikabulkan", label: "Dikabulkan", className: "State-ACT" },
																				]}
																			/>
																		)}
																	</Field>
																	<ErrorMessage name="status" component="div" className="form-text text-danger" />
																</div>
															</FormGroup>
															<FormGroup>
																<label className="row-form-label">Dokumen Jawaban<span className="text-danger">*</span>:</label>
																<div className="row-md-10">
																	<Field name="dokumen">
																		{({ field, form }) => (
																			<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 {...getInputProps()} />
																							<div className="dropzone-previews flex">
																								<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>
																							<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>
															<FormGroup row>
																<div className="col-xl-10">
																	<Button color className="color-3e3a8e btn-login" type="submit">
																		<span className="font-color-white">Simpan</span>
																	</Button>
																</div>
															</FormGroup>
														</Form>
													)}
												</Formik>
											</Col>
										</Row>
									</CardBody>
								</Card>
							</Col>
						) : (
							<Loader />
						)}
						<Col xl={3}>{pt ? <DetailPT data={pt} /> : <Loader />}</Col>
					</Row>
					{sanksi.data && (
						<Row>
							<Col>
								<Riwayat data={sanksi.data.jawaban.banding} />
							</Col>
						</Row>
					)}
				</div>
				<Modal isOpen={this.state.modal} toggle={this.toggleModal}>
					<ModalBody>Apakah anda yakin ingin mengubah jawaban sebelumnya?</ModalBody>
					<ModalFooter>
						<Button color="primary" onClick={this.handelSimpan}>
							Ya
						</Button>{" "}
						<Button color="secondary" onClick={this.toggleModal}>
							Tidak
						</Button>
					</ModalFooter>
				</Modal>
			</ContentWrapper>
		);
	}
}

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