import React, { Component } from "react";
import Router from "next/router";
import { getPelanggaran } from "@/actions/pelanggaran";
import { createPelaporan } from "@/actions/pelaporan";
import Select from "react-select";
import { Row, Col, FormGroup, Input } from "reactstrap";
import { connect } from "react-redux";

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;
export class InputData extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dropdownOpen: false,
			splitButtonOpen: false,
			selectedOptionMulti: [],
			stat: "Waiting to add files..",
			pelaporanNumber: Math.floor(Date.now() * Math.random()),
			keteranganLaporan: "",
			files: [],
			pelanggaran: [],
		};
	}

	componentDidMount = async () => {
		const pelanggaran = await getPelanggaran();
		this.setState({ pelanggaran });
	};

	optionsJenisPelanggaran = (pelanggaran) => {
		return pelanggaran.data.map((e) => ({ value: e._id, label: e.pelanggaran, className: "State-ACT" }));
	};

	setKeteranganPelaporan = (e) => {
		this.setState({ keteranganLaporan: e.target.value });
	};

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

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

	handleChangeSelectMulti = (selectedOptionMulti) => {
		this.setState({ selectedOptionMulti });
	};

	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 (e) => {
		const { user } = this.props;
		e.preventDefault();
		const formdata = new FormData();
		formdata.append("number", this.state.pelaporanNumber);
		formdata.append("user_id", user._id);
		formdata.append("pt_id", this.props.query.ptId);
		formdata.append("description", this.state.keteranganLaporan);
		formdata.append("is_public", false);
		formdata.append("pelanggaran", this.state.selectedOptionMulti.map((e) => e.value).join());
		if (this.state.files.length > 0) {
			this.state.files.forEach((e) => {
				formdata.append("files", e);
			});
		}

		const create = await createPelaporan(formdata);
		// console.log(create);
		// console.log(create);
		// await this.props.dispatch(createPelaporan(formdata));
		// this.props.dispatch(listPelaporan());
		if (create) {
			Router.push({
				pathname: "/app/pelaporan",
			});
		}
	};

	render() {
		const { selectedOptionMulti, files, pelanggaran } = 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 (
			<form className="form-horizontal" method="get" action="/" onSubmit={this.onSubmit}>
				<FormGroup row>
					<label className="col-md-2 col-form-label">Nomor Pelaporan</label>
					<div className="col-md-10">
						<Input type="text" disabled value={this.state.pelaporanNumber} />
						<span className="form-text">Nomor pelaporan akan digenerate otomatis dari sistem</span>
					</div>
				</FormGroup>
				<FormGroup row>
					<label className="col-md-2 col-form-label">Jenis Pelanggaran</label>
					<div className="col-md-10">
						<Select instanceId={selectInstanceId + 1} isMulti value={selectedOptionMulti} onChange={this.handleChangeSelectMulti} options={pelanggaran.data ? this.optionsJenisPelanggaran(pelanggaran) : []} required />
						<span className="form-text">Pilih Jenis Pelanggaran</span>
					</div>
				</FormGroup>
				<FormGroup row>
					<label className="col-md-2 col-form-label">Keterangan Laporan</label>
					<div className="col-md-10">
						<Input type="textarea" value={this.state.keteranganLaporan} onChange={this.setKeteranganPelaporan} required />
						<span className="form-text">Deskripsi pelaporan minimum karakter 50 maksimum 200 karakter</span>
					</div>
				</FormGroup>
				<FormGroup row>
					<label className="col-md-2 col-form-label">Upload File Pendukung</label>
					<div className="col-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 row>
					<div className="col-xl-10">
						<button className="btn btn-sm btn-primary" type="submit">
							Submit Laporan
						</button>
					</div>
				</FormGroup>
			</form>
		);
	}
}

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