import React, { Component } from "react";
import Router from "next/router";
import BasePage from "@/components/Layout/BasePage";
import { getPT } from "@/actions/PT";
import { getPelanggaran } from "@/actions/pelanggaran";
import { createPelaporan } from "@/actions/pelaporan";
import { notifLaporanBaru } from "@/actions/notifikasi";
import Select from "react-select";
import AsyncSelect from "react-select/async";
import { Row, Col, FormGroup, Input, Card, CardBody, Button, CustomInput, Navbar, NavItem, NavLink, NavbarBrand, NavbarToggler, Nav, Collapse } from "reactstrap";
import Link from "next/link";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { createPublicUser } from "@/actions/user";

const loadOptions = (inputValue, callback) => {
	setTimeout(async () => {
		const pt = await getPT({ search: inputValue });
		const data = pt.data.map((e) => ({ value: e.id, label: e.nama, className: "State-ACT" }));
		callback(data);
	}, 1000);
};

const menu = [
	{
		title: "Home",
		path: "/app",
	},
	{
		title: "Buat Laporan",
		path: "/laporan/new",
	},
	{
		title: "Pemantauan",
		path: "/pemantauan",
	},
];
const selectInstanceId = 1;
class App extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isOpen: false,
			inputValue: "",
			pelaporanNumber: Math.floor(Date.now() * Math.random()),
			nama: "",
			alamat: "",
			no_hp: "",
			email: "",
			fileIdentitas: null,
			pelanggaran: [],
			selectedPerguruanTinggi: {},
			selectedJenis: [],
			keteranganLaporan: "",
			files: [],
			isPrivate: false,
			confirm: false,
			msgError: [],
		};
	}

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

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

	toggleCollapse = () => {
		this.setState({
			isOpen: !this.state.isOpen,
		});
	};

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

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

	handleChangeSelectJenis = (selectedJenis) => {
		this.setState({ selectedJenis });
	};

	handleChangeSelectPerguruanTinggi = (selectedPerguruanTinggi) => {
		this.setState({ selectedPerguruanTinggi });
	};

	handleInputChange = (newValue) => {
		const inputValue = newValue.replace(/\W/g, "");
		this.setState({ inputValue });
		return inputValue;
	};

	handleKirim = async (e) => {
		e.preventDefault();
		const { nama } = this.state;
		const user_id = await this.createUser();
		if (user_id) {
			const laporan = await this.createLaporan(user_id, nama);
			if (laporan) {
				await this.sendNotif();
				Router.push("/laporan/new");
			}
		}

		// validasi
		// if (nama === '')  msgError.push({nama: 'Wajib diisi'})
	};

	sendNotif = async () => {
		const { nama, no_hp, selectedPerguruanTinggi, keteranganLaporan, pelaporanNumber, selectedJenis } = this.state;
		const description = `${selectedJenis.map((e) => e.label).join(", ")} dengan keterangan ${keteranganLaporan}`;
		// const description = keteranganLaporan;
		return await notifLaporanBaru({ nama, pt_name: selectedPerguruanTinggi.label, description, no_laporan: pelaporanNumber.toString() });
	};

	createUser = async () => {
		const { nama, alamat, no_hp, email, fileIdentitas, isPrivate } = this.state;
		const dataUser = new FormData();
		dataUser.append("nama", nama);
		dataUser.append("no_hp", no_hp);
		dataUser.append("email", email);
		dataUser.append("alamat", alamat);
		dataUser.append("files", fileIdentitas);
		dataUser.append("isPrivate", isPrivate);
		const userPublic = await createPublicUser(dataUser);
		if (userPublic.success) return userPublic.created._id;
		return false;
	};

	createLaporan = async (user_id, nama) => {
		const { pelaporanNumber, selectedPerguruanTinggi, keteranganLaporan, selectedJenis, files } = this.state;
		const formdata = new FormData();
		formdata.append("number", pelaporanNumber);
		formdata.append("pt_id", selectedPerguruanTinggi.value);
		formdata.append("user_id", user_id);
		formdata.append("description", keteranganLaporan);
		formdata.append("is_public", true);
		formdata.append("nama", nama);
		formdata.append("pelanggaran", selectedJenis.map((e) => e.value).join());
		if (files.length > 0) {
			Array.from(files).forEach((e) => {
				formdata.append("files", e);
			});
		}
		const create = await createPelaporan(formdata);
		if (create.success) return create;
		return false;
	};

	render() {
		const { selectedJenis, pelanggaran, confirm, isPrivate } = this.state;
		return (
			<div>
				<Navbar color="info" expand="md" dark>
					<NavbarBrand href="/">
						<img className="img-fluid" src="/static/img/logo-single.png" alt="App Logo" /> Sidali Dikti
					</NavbarBrand>
					<NavbarToggler onClick={this.toggleCollapse} />
					<Collapse isOpen={this.state.isOpen} navbar>
						<Nav className="ml-auto" navbar>
							{menu.map((e) => (
								<NavItem active={e.path === this.props.pathname ? true : false}>
									<Link href={e.path}>
										<NavLink style={{ cursor: "pointer" }}>{e.title}</NavLink>
									</Link>
								</NavItem>
							))}
						</Nav>
					</Collapse>
				</Navbar>
				<ContentWrapper>
					<Row>
						<Col lg={8} className="block-center d-block ">
							<Card className="card-default">
								<CardBody>
									<form className="form-horizontal" method="post" onSubmit={this.onSubmit}>
										<p className="lead bb">Identitas Pelapor</p>
										<FormGroup row>
											<div className="col-xl-10">
												<div className="checkbox c-checkbox">
													<label>
														<Input type="checkbox" onChange={(e) => this.setState({ isPrivate: !isPrivate })} defaultChecked="" />
														<span className="fa fa-check"></span>Klik jika ingin merahasiakan identitas anda
													</label>
												</div>
											</div>
										</FormGroup>
										<FormGroup row>
											<label className="col-md-2 col-form-label">Nama Pelapor</label>
											<div className="col-md-10">
												<Input type="text" value={this.state.nama} onChange={(e) => this.setState({ nama: e.target.value })} required />
											</div>
										</FormGroup>
										<FormGroup row>
											<label className="col-md-2 col-form-label">Nomor yang dapat dihubungi</label>
											<div className="col-md-10">
												<Input type="text" value={this.state.no_hp} onChange={(e) => this.setState({ no_hp: e.target.value })} required />
											</div>
										</FormGroup>
										<FormGroup row>
											<label className="col-md-2 col-form-label">Email</label>
											<div className="col-md-10">
												<Input type="email" value={this.state.email} onChange={(e) => this.setState({ email: e.target.value })} required />
											</div>
										</FormGroup>
										<FormGroup row>
											<label className="col-md-2 col-form-label">Alamat</label>
											<div className="col-md-10">
												<Input type="textarea" value={this.state.alamat} onChange={(e) => this.setState({ alamat: e.target.value })} required />
											</div>
										</FormGroup>
										<FormGroup row>
											<label className="col-md-2 col-form-label">Foto Kartu Identitas</label>
											<div className="col-md-10">
												<Input type="file" onChange={(e) => this.setState({ fileIdentitas: e.target.files[0] })} />
											</div>
										</FormGroup>
										<p className="lead bb">Detail Laporan</p>
										<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} />
											</div>
										</FormGroup>
										<FormGroup row>
											<label className="col-md-2 col-form-label">Perguruan Tinggi yang Dilaporkan</label>
											<div className="col-md-10">
												<AsyncSelect cacheOptions loadOptions={loadOptions} defaultOptions onChange={this.handleChangeSelectPerguruanTinggi} onInputChange={this.handleInputChange} required />
											</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={selectedJenis}
													onChange={this.handleChangeSelectJenis}
													options={pelanggaran.data ? this.optionsJenisPelanggaran(pelanggaran) : []}
													required
												/>
											</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 />
											</div>
										</FormGroup>
										<FormGroup row>
											<label className="col-md-2 col-form-label">File Pendukung</label>
											<div className="col-md-10">
												<Input type="file" multiple onChange={(e) => this.setState({ files: e.target.files })} />
											</div>
										</FormGroup>
										<FormGroup row>
											<div className="col-xl-10">
												<div className="checkbox c-checkbox">
													<label>
														<Input type="checkbox" onChange={(e) => this.setState({ confirm: !confirm })} defaultChecked="" />
														<span className="fa fa-check"></span>Klik jika data yang anda laporkan sudah benar
													</label>
												</div>
											</div>
										</FormGroup>
										<FormGroup row>
											<div className="col-12 col-lg-2">
												<Button color="info" block type="submit" onClick={this.handleKirim}>
													Kirim Laporan
												</Button>
											</div>
										</FormGroup>
									</form>
								</CardBody>
							</Card>
						</Col>
					</Row>
				</ContentWrapper>
			</div>
		);
	}
}

App.Layout = BasePage;

export default App;
