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/Keberatan/Riwayat";
import { getSanksi } from "@/actions/sanksi";
import { addJawabanKeberatan } from "@/actions/keberatan";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { Row, Col, Card, CardBody, FormGroup, Input, Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
import { getPT } from "@/actions/PT";

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;

class DetailKeberatan extends Component {
	constructor(props) {
		super(props);
		this.state = {
			modal: false,
			selectedOption: null,
			files: [],
			keterangan: "",
			sanksi: {},
			pt: {},
		};
	}

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

	componentDidMount = async () => {
		const { query } = this.props;
		const sanksi = await getSanksi(query);
		const pt = await getPT({ id: query.ptId });
		this.setState({ pt, sanksi });
	};

	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 (e) => {
		e.preventDefault();
		const { keterangan, selectedOption } = this.state;
		const { noSanksi, ptId } = this.props.query;
		const formdata = new FormData();
		formdata.append("description", keterangan);
		formdata.append("status", selectedOption.value);
		if (this.state.files.length > 0) {
			this.state.files.forEach((e) => {
				formdata.append("files", e);
			});
			const added = await addJawabanKeberatan({ noSanksi, ptId }, formdata);
			if (added) {
				Router.push({
					pathname: "/app/keberatan",
				});
			}
		}

		
	};

	render() {
		const { files, sanksi, pt } = 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 /> */}
				<div className="p-3">
					<div className="content-heading">
						<div>Permohonan Keberatan</div>
						<div className="ml-auto">
							<Link href="/app/keberatan">
								<button className="btn btn-sm btn-secondary text-sm">&lt; back</button>
							</Link>
						</div>
					</div>
					<Row>
						<Col xl="9">
							<Card className="card-default">
								<CardBody>
									<Row>
										<Col lg={12}>{sanksi.data && sanksi.data.length && <DetailSanksi data={sanksi.data[0]} />}</Col>
									</Row>
									<Row>
										<Col lg={12}>{sanksi.data && sanksi.data.length && <PermohonanPT data={sanksi.data[0].sanksi.keberatan} title="Permohonan Keberatan" />}</Col>
									</Row>
									<Row>
										<Col lg={12}>
											<p className="lead bb">Jawaban</p>
											<form className="form-horizontal" method="get" action="/" onSubmit={this.onSubmit}>
												<FormGroup>
													<label className="row-form-label">Status:</label>
													<div className="row-md-10">
														<Select
															instanceId={selectInstanceId + 1}
															value={this.state.selectedOption}
															onChange={this.handleChangeSelect}
															options={[
																{ value: "Menolak", label: "Menolak", className: "State-ACT" },
																{ value: "Mengubah Keputusan", label: "Mengubah Keputusan", className: "State-ACT" },
																{ value: "Membatalkan Keputusan", label: "Membatalkan Keputusan", className: "State-ACT" },
															]}
															required
														/>
														{/* <span className="form-text">Pilih Jenis Pelanggaran</span> */}
													</div>
												</FormGroup>
												<FormGroup>
													<label className="row-form-label">Keterangan Jawaban:</label>
													<div className="row-md-10">
														<Input type="textarea" value={this.state.keterangan} onChange={(e) => this.setState({ keterangan: e.target.value })} required />
														{/* <span className="form-text">Deskripsi pelaporan minimum karakter 50 maksimum 200 karakter</span> */}
													</div>
												</FormGroup>
												<FormGroup>
													<label className="row-form-label">Dokumen Jawaban:</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={sanksi.data && sanksi.data.length && sanksi.data[0].sanksi.keberatan.jawaban ? this.toggleModal : this.handelSimpan}>
													Simpan
												</Button>
												{/* </div>
												</FormGroup> */}
											</form>
										</Col>
									</Row>
								</CardBody>
							</Card>
						</Col>
						<Col xl="3">{pt?.data && <DetailPT data={pt.data[0]} />}</Col>
					</Row>
					<Row>
						<Col>{sanksi.data && sanksi.data.length && <Riwayat data={sanksi.data[0].sanksi.keberatan.jawaban} />}</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>
		);
	}
}

export default DetailKeberatan;
