import React, { Component } from "react";
import Router from "next/router";
import { getOneSanksi } from "@/actions/sanksi";
import { addDocPerbaikan } from "@/actions/docPerbaikan";
import Link from "next/link";
import Header from "@/components/Main/Header";
import DetailPT from "@/components/Main/DetailPT";
import DetailSanksi from "@/components/Main/DetailSanksi";
import Riwayat from "@/components/PT/DocPerbaikan/Riwayat";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { Row, Col, Card, CardBody, FormGroup, Button, Input } from "reactstrap";
import { connect } from "react-redux";
import { notifDocPerbaikan } from "@/actions/notifikasi";
import Loader from "@/components/Common/Loader";
import { toast } from "react-toastify";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";

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 perbaikanSchema = Yup.object().shape({
	keterangan: Yup.string().min(3).max(200).required("Harap diisi"),
	dokumen: Yup.array().min(1, "minimal terdapat 1 dokumen").required("Harap 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 DetailPerbaikanDoc extends Component {
	constructor(props) {
		super(props);
		this.state = {
			files: [],
			sanksi: {},
			keterangan: "",
			pt: null,
		};
	}

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

	componentDidMount = async () => {
		const { token, query } = this.props;
		const sanksi = await getOneSanksi(token, query.id);
		this.setState({ sanksi, pt: sanksi.data.laporan.pt });
	};

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

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

	handleKirim = async (data, { resetForm }) => {
		const { token, query } = this.props;
		const { id } = query;
		const formdata = new FormData();
		formdata.append("keterangan", data.keterangan);
		this.state.files.forEach((e) => {
			formdata.append("dokumen", e);
		});
		const toastid = toast.loading("Please wait...");
		const added = await addDocPerbaikan(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 });
			const sanksi = await getOneSanksi(token, id);
			this.setState({ sanksi, files: [] });
			resetForm();
			// Router.push({
			// 	pathname: "/app/pt/dokumen-perbaikan",
			// });
		}
	};

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

		const thumbs = files.map((file, index) => (
			<div className="text-left" 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>
				{pt && <Header data={pt} />}
				<div className="p-3">
					<div className="content-heading">
						<span className="font-color-white">Dokumen Perbaikan</span>
						<div className="ml-auto">
							<Link href="/pt/dokumen-perbaikan">
								<Button className="color-3e3a8e" 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} />
												<p className="lead bb">Dokumen Perbaikan</p>
												<Formik
													initialValues={{
														keterangan: "",
														dokumen: [],
													}}
													validationSchema={perbaikanSchema}
													onSubmit={this.handleKirim}
												>
													{() => (
														<Form className="form-horizontal">
															<FormGroup>
																<label className="row-form-label">Keterangan Dokumen:</label>
																<div className="row-md-10">
																	<Field name="keterangan">{({ field }) => <Input type="textarea" {...field} />}</Field>
																	<ErrorMessage name="keterangan" component="div" className="form-text text-danger" />
																	{/* <span className="form-text">Deskripsi pelaporan minimum karakter 50 maksimum 200 karakter</span> */}
																</div>
															</FormGroup>
															<FormGroup>
																<label className="row-form-label">Upload Dokumen:</label>
																{/* <div className="col-md-10">
																	<Field name="dokumen">{({ field, form }) => <Input type="file" multiple onChange={(e) => form.setFieldValue(field.name, Array.from(e.currentTarget.files))} />}</Field>
																	<ErrorMessage name="dokumen" component="div" className="form-text text-danger" />
																	<p className="mrgn-top-5">
																		Ukuran setiap dokumen maksimal 15mb
																	</p>
																</div> */}
																<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-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={this.clearFiles}>
																										Clear files
																									</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" type="submit">
																		<span className="font-color-white">Kirim</span>
																	</Button>
																</div>
															</FormGroup>
														</Form>
													)}
												</Formik>
											</Col>
										</Row>
									</CardBody>
								</Card>
							</Col>
						) : (
							<Loader />
						)}
						<Col xl="3">{pt && <DetailPT data={pt} />}</Col>
					</Row>
					{sanksi.data && (
						<Row>
							<Col>
								<Riwayat data={sanksi.data.perbaikan} />
							</Col>
						</Row>
					)}
				</div>
			</ContentWrapper>
		);
	}
}

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