import React, { Component } from "react";
import Router from "next/router";
import { getSanksi } 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";

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

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

	componentDidMount = async () => {
		const { user } = this.props;
		const { noSanksi } = this.props.query;
		const sanksi = await getSanksi({ noSanksi, ptId: user.peran[0].organisasi.id });
		this.setState({ 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 (e) => {
		e.preventDefault();
		const { keterangan, sanksi } = this.state;
		const { noSanksi } = this.props.query;
		const { user } = this.props;
		const org_id = user.peran[0].organisasi.id;
		const formdata = new FormData();
		formdata.append("description", keterangan);
		if (this.state.files.length > 0) {
			this.state.files.forEach((e) => {
				formdata.append("files", e);
			});
			const added = await addDocPerbaikan({ noSanksi, ptId: org_id }, formdata);
			if (added) {
				await notifDocPerbaikan({ lembaga: sanksi.data[0].sanksi.user.lembaga, pt_name: user.peran[0].organisasi.nama, no_sanksi: sanksi.data[0].sanksi.no_sanksi });
				Router.push({
					pathname: "/app/pt/dokumen-perbaikan",
				});
			}
		}
	};

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

		const thumbs = files.map((file, index) => (
			<Col md={3} key={index}>
				<img className="img-fluid mb-2" src={file.preview} alt="Item" />
			</Col>
		));

		return (
			<ContentWrapper unwrap>
				<Header data={this.props.pt[0]} />
				<div className="p-3">
					<div className="content-heading">
						<div>Dokumen Perbaikan</div>
						<div className="ml-auto">
							<Link href="/app/pt/dokumen-perbaikan">
								<button className="btn btn-sm btn-secondary text-sm">&lt; back</button>
							</Link>
						</div>
					</div>
					<Row>
						{sanksi?.data ? (
							<Col xl="9">
								<Card className="card-default">
									<CardBody>
										<Row>
											<Col lg={12}>
												<DetailSanksi data={sanksi.data[0]} />
												<p className="lead bb">Dokumen Perbaikan</p>
												<form className="form-horizontal" method="get" action="/" onSubmit={this.onSubmit}>
													<FormGroup>
														<label className="row-form-label">Keterangan:</label>
														<div className="row-md-10">
															<Input type="textarea" value={this.state.keterangan} onChange={(e) => this.setState({ keterangan: e.target.value })} required />
														</div>
													</FormGroup>
													<FormGroup>
														<label className="row-form-label">Upload Dokumen:</label>
														<div className="row-md-10">
															<DropzoneWrapper className="" onDrop={this.onDrop}>
																{({ getRootProps, getInputProps, isDragActive }) => {
																	return (
																		<div {...getRootProps()} className={"dropzone card p-3 " + (isDragActive ? "dropzone-drag-active" : "")}>
																			<input {...getInputProps()} />
																			<div className="dropzone-previews flex">
																				{this.state.files.length > 0 ? <Row>{thumbs}</Row> : <div className="text-center dz-default dz-message">Drop files here to upload</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>
														</div>
													</FormGroup>
													<FormGroup>
														<div className="row-xl-10">
															<Button color="primary" onClick={this.handleKirim} type="submit">
																Kirim
															</Button>
														</div>
													</FormGroup>
												</form>
											</Col>
										</Row>
									</CardBody>
								</Card>
							</Col>
						) : (
							<Loader />
						)}
						<Col xl="3">{this.props.pt && <DetailPT data={this.props.pt[0]} />}</Col>
					</Row>
					{sanksi?.data && (
						<Row>
							<Col>
								<Riwayat data={sanksi.data[0].sanksi.doc_perbaikan} />
							</Col>
						</Row>
					)}
				</div>
			</ContentWrapper>
		);
	}
}

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