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


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({
    from_date: Yup.date().required("Wajib diisi"),
    to_date: Yup.date().required("Wajib diisi"),
    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: {},
        };
    }

    async componentDidMount() {
        const { token, query } = this.props;
        const { id } = query;
        const sanksi = await getOneSanksi(token, id);
        this.setState({ sanksi })
        console.log(this.state.sanksi)
    }


    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 };
    };


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

        }

    };
    render() {
        const { files, sanksi } = 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">Perpanjangan Sanksi</p>
                    <Formik
                        initialValues={{
                            dokumen: [],
                            from_date: "",
                            to_date: "",

                        }}
                        validationSchema={rekomendasiSchema}
                        onSubmit={async (data) => {
                            this.setState({ data });
                            await this.handelSimpan();
                        }}
                    >
                        {() => (
                            <Form className="form-horizontal">
                                <FormGroup row className="mt-3">
                                    <label className="col-md-2 col-form-label">Tanggal Perpanjangan Sanksi :</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>
                                <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);
