import React, { Component } from "react";
import { Row, Col, Card, CardBody, FormGroup, Input, Button, Modal, ModalHeader, ModalBody, ModalFooter, CardHeader, CardTitle } from "reactstrap";
import { toast } from "react-toastify";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { connect } from "react-redux";
import { getOneSanksi, update } from "@/actions/sanksi";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { addDays, addMonths } from 'date-fns';
import id from 'date-fns/locale/id';
import moment from "moment";
import 'moment/min/locales';
moment.locale('id');
import Router from "next/router";
import { getPelanggaranSanksi } from "@/actions/pelanggaran";
import Select from "react-select";


const selectInstanceId = 1;
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 rekomendasiSchema = Yup.object().shape({
    no_sanksi: Yup.string().required("Wajib isi Nomor Sanksi"),
    keterangan: Yup.string().min(3, "Minimal 3 Huruf").max(200).required("Wajib isi keterangan"),
    from_date: Yup.date().required("Wajib diisi"),
    to_date: Yup.date().required("Wajib diisi"),
    sanksi: Yup.array().required("Wajib isi pelanggaran"),
    dokumen: Yup.array().required("Wajib 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 InputTanggal extends Component {
    constructor(props) {
        super(props);
        const tmt_awal = new Date();
        this.state = {
            dropdownOpen: false,
            splitButtonOpen: false,
            files: [],
            sanksi: {},
            data: {},
            from_date: "",
            to_date: "",
            startDay: tmt_awal,
            sanksi: {},
            keteranganLaporan: "",
            tmtCheck: false,
            listSanksi: ""
        };
    }

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


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

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

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

    static getInitialProps = async ({ query }) => {
        return { query };
    };
    setKeteranganPelaporan = (e) => {
        this.setState({ keteranganLaporan: e.target.value });
    };
    handleTmtCheck = () => {
        this.setState({ tmtCheck: !this.state.tmtCheck });
    };


    handelSimpan = async (data) => {
        const { token, query } = this.props;
        const { id } = query;
        const formdata = new FormData();
        formdata.append("no_sanksi", data.no_sanksi);
        formdata.append("keterangan", data.keterangan);
        formdata.append("from_date", data.from_date);
        formdata.append("to_date", data.to_date);
        formdata.append("sanksi", JSON.stringify(data.sanksi));
        this.state.files.forEach((e) => {
            formdata.append("dokumen", e);
        });
        const toastid = toast.loading("Please wait...");
        const added = await update(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 });
            Router.push("/app/naik-sanksi");

        }

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

        const thumbs = files.map((file, index) => (
            <div md={3} key={index}>
                <span className="text-left">{index + 1}.{file.name}</span>
            </div>
        ));
        return (
            <Card className="card-default">
                <CardBody>
                    <p className="lead bb">Dokumen Surat Naik Sanksi</p>
                    <Formik
                        initialValues={{
                            no_sanksi: "",
                            keterangan: "",
                            from_date: "",
                            to_date: "",
                            sanksi: [],
                            dokumen: [],
                        }}
                        validationSchema={rekomendasiSchema}
                        onSubmit={this.handelSimpan}
                    >
                        {() => (
                            <Form className="form-horizontal">
                                <FormGroup row>
                                    <label className="col-md-2 col-form-label">Nomor Surat</label>
                                    <div className="col-md-10">
                                        <Field name="no_sanksi">{({ field }) => <Input type="textarea" placeholder="Nomor Surat" {...field} />}</Field>
                                        <ErrorMessage name="no_sanksi" component="div" className="form-text text-danger" />
                                    </div>
                                </FormGroup>
                                <FormGroup row>
                                    <label className="col-md-2 col-form-label">Keterangan</label>
                                    <div className="col-md-10">
                                        <Field name="keterangan">{({ field }) => <Input type="textarea" placeholder="Keterangan" {...field} />}</Field>
                                        <ErrorMessage name="keterangan" component="div" className="form-text text-danger" />
                                    </div>
                                </FormGroup>
                                <FormGroup row>
                                    <label className="col-md-2 col-form-label">Tidak Perlu TMT</label>
                                    <div className="col-md-10 mt-2">
                                        <div className="checkbox c-checkbox">
                                            <label>
                                                <Input type="checkbox" onChange={this.handleTmtCheck} defaultChecked={this.state.tmtCheck} />
                                                <span className="fa fa-check"></span></label>
                                        </div>
                                    </div>
                                </FormGroup>
                                {this.state.tmtCheck && (
                                    <FormGroup row className="mt-3">
                                        <label className="col-md-2 col-form-label">Tanggal Penetapan Sanksi</label>
                                        <span className="col-sm-3 float-left">
                                            <Field name="from_date">
                                                {({ field, form }) => (
                                                    <DatePicker
                                                        selected={this.state.from_date}
                                                        onChange={(from_date) => {
                                                            this.setState({ from_date })
                                                            form.setFieldValue(field.name, from_date);
                                                        }}
                                                        dateFormat="dd/MM/yyyy"
                                                        maxDate={this.state.startDay}
                                                        placeholderText="Dari Tanggal"
                                                        locale={id}
                                                        className="form-control bg-white"
                                                    />
                                                )}
                                            </Field>
                                            <ErrorMessage name="from_date" component="div" className="form-text text-danger" />
                                        </span>
                                    </FormGroup>
                                )}
                                {!this.state.tmtCheck && (
                                    <FormGroup row className="mt-3">
                                        <label className="col-md-2 col-form-label">Isi TMT :</label>
                                        <div className="col-md-6">
                                            <Row >
                                                <Col>
                                                    <FormGroup>
                                                        <Field name="from_date">
                                                            {({ field, form }) => (
                                                                <DatePicker
                                                                    selected={this.state.from_date}
                                                                    onChange={(from_date) => {
                                                                        this.setState({ from_date })
                                                                        form.setFieldValue(field.name, from_date);
                                                                    }}
                                                                    dateFormat="dd/MM/yyyy"
                                                                    maxDate={this.state.startDay}
                                                                    placeholderText="Dari Tanggal"
                                                                    locale={id}
                                                                    className="form-control bg-white"
                                                                />
                                                            )}
                                                        </Field>
                                                        <ErrorMessage name="from_date" component="div" className="form-text text-danger" />
                                                    </FormGroup>
                                                </Col>
                                                <Col>
                                                    <FormGroup>
                                                        <Field name="to_date">
                                                            {({ field, form }) => (
                                                                <DatePicker
                                                                    selected={this.state.to_date}
                                                                    onChange={(to_date) => {
                                                                        this.setState({ to_date })
                                                                        form.setFieldValue(field.name, to_date);
                                                                    }}
                                                                    dateFormat="dd/MM/yyyy"
                                                                    minDate={this.state.from_date}
                                                                    maxDate={addMonths(new Date(this.state.from_date), 6)}
                                                                    placeholderText="Sampai tanggal"
                                                                    locale={id}
                                                                    className="form-control bg-white"
                                                                />
                                                            )}
                                                        </Field>
                                                        <ErrorMessage name="to_date" component="div" className="form-text text-danger" />
                                                    </FormGroup>
                                                </Col>
                                            </Row>
                                        </div>
                                    </FormGroup>
                                )}
                                {!this.state.tmtCheck && (
                                    <FormGroup row className="mt-1">
                                        <label className="col-md-2 col-form-label">TMT berlaku</label>
                                        <div className="col-md-10 mt-2">
                                            <b>{this.state.from_date ? moment(this.state.from_date).format("DD-MM-YYYY") : "-"}</b> hingga <b>{this.state.to_date ? moment(this.state.to_date).format("DD-MM-YYYY") : "-"}</b>
                                        </div>
                                    </FormGroup>
                                )}
                                {!this.state.tmtCheck && (
                                    <FormGroup row className="mt-1">
                                        <label className="col-md-2 col-form-label">TMT</label>
                                        <div className="col-md-10 mt-2">
                                            <b>{this.state.to_date ? moment(this.state.to_date).diff(this.state.from_date, 'month') : "-"} bulan</b>
                                        </div>
                                    </FormGroup>
                                )}

                                <FormGroup row className="mt-3">
                                    <label className="col-md-2 col-form-label">List sanksi </label>
                                    <div className="col-md-10">
                                        <Field name="sanksi">{({ field, form }) => <Select
                                            options={this.props.listSanksi.map(e => ({ value: e, label: e }))}
                                            isMulti
                                            onChange={(e) => {
                                                form.setFieldValue(field.name, e);
                                            }}
                                        />}</Field>
                                        <ErrorMessage name="sanksi" component="div" className="form-text text-danger" />
                                    </div>
                                </FormGroup>
                                <FormGroup row className="mt-3">
                                    <label className="col-md-2 col-form-label">Dokumen Perpanjangan Sanksi : <span className="text-danger">*</span></label>
                                    <div className="col-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-previews flex">
                                                                    <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">Upload dokumen rekomendasi delegasi</h5>
                                                                            </div>
                                                                        }
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div className="d-flex align-items-center">
                                                                    <small className="ml-auto">
                                                                        <button
                                                                            type="button"
                                                                            className="btn btn-link"
                                                                            onClick={(e) => {
                                                                                this.clearFiles(e);
                                                                                form.setFieldValue(field.name, []);
                                                                            }}
                                                                        >
                                                                            Reset dokumen
                                                                        </button>
                                                                    </small>
                                                                </div>
                                                            </div>
                                                        );
                                                    }}
                                                </DropzoneWrapper>
                                            )}
                                        </Field>
                                    </div>
                                </FormGroup>
                                <FormGroup row>
                                    <div className="col-xl-10">
                                        <Button color className="color-3e3a8e btn-login" type="submit">
                                            <span className="font-color-white">Kirim</span>
                                        </Button>
                                    </div>
                                </FormGroup>
                            </Form>
                        )}
                    </Formik>
                </CardBody>
            </Card>
        );
    }
}

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