import React, { Component } from "react";
import Router from "next/router";
import BasePage from "@/components/Layout/BasePage";
import { ptPublic } from "@/actions/PT";
import { getPelanggaranPublic } from "@/actions/pelanggaran";
import { createLaporanPublic } from "@/actions/pelaporan";
import { notifLaporanBaru } from "@/actions/notifikasi";
import Select from "react-select";
import AsyncSelect from "react-select/async";
import { CopyToClipboard } from "react-copy-to-clipboard";
import {
  Row,
  Col,
  FormGroup,
  Input,
  Card,
  CardBody,
  Button,
  CustomInput,
  Navbar,
  NavItem,
  NavLink,
  NavbarBrand,
  NavbarToggler,
  Nav,
  Collapse,
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  FormFeedback,
} from "reactstrap";
import Link from "next/link";
import ContentWrapper from "@/components/Layout/ContentWrapper";
import { createPublicUser } from "@/actions/user";
import { ToastContainer, toast } from "react-toastify";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import swal from "sweetalert2";

import "react-toastify/dist/ReactToastify.css";

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 laporanSchema = Yup.object().shape({
  no_laporan: Yup.string().required(),
  no_hp: Yup.number().notRequired(),
  nama: Yup.string().notRequired(),
  setuju: Yup.boolean().isTrue("Harap diceklis"),
  alamat: Yup.string()
    .min(3, "Minimal 3 huruf")
    .max(200, "Maksimal 200 huruf")
    .notRequired(),
  keterangan: Yup.string()
    .min(3, "Minimal 3 huruf")
    .max(200, "Maksimal 200 huruf")
    .required("Wajib diisi"),
  email: Yup.string().email().notRequired(),
  pelanggaran_id: Yup.array()
    .min(1, "Minimal terdapat 1 jenis pelanggaran")
    .required("Wajib diisi"),
  pt_id: Yup.string().required("Wajib diisi"),
  foto: Yup.array()
    .notRequired()
    .test("filesize", "Maksimal ukuran foto 15mb", checkIfFilesAreTooBig)
    .test("type", "harus jpeg/png", checkIfFilesAreCorrectType),
  dokumen: Yup.array()
    .min(0, " ")
    .notRequired()
    .test(
      "filesize",
      "Maksimal ukuran setiap dokumen 15mb",
      checkIfFilesAreTooBig
    ),
  is_private: Yup.boolean().notRequired(),
});

const loadOptions = (inputValue, callback) => {
  setTimeout(async () => {
    const pt = await ptPublic({ 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: [],
      modal: false,
      modalNotnoHP: false,
      user: {},
      kode: "",
      error: null,
      data: {},
      token: "",
      loading: false,
      disablecancel: false,
      disablekirim: false,
      disablekirim2: false,
      disablekirim3: false,
      loading2: false,
      kodeVerifNotOK: false,
    };
  }

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

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

  toggleModal = (no_hp = null) => {
    if (no_hp) {
      this.setState({ modal: !this.state.modal })
    } else {
      this.setState({ modalNotnoHP: !this.state.modalNotnoHP });
    }
  };
  // disableKirim = (modalNotnoHP = false) => {
  //   if (modalNotnoHP == false) {
  //     this.setState({ disableKirim: true })

  //   } else {
  //     this.setState({ disableKirim: false })
  //   }
  // }

  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 (data, { resetForm }) => {
    const formdata = new FormData();
    formdata.append("no_laporan", data.no_laporan);
    formdata.append("pt_id", data.pt_id);
    formdata.append("nama", data.nama);
    formdata.append("email", data.email);
    formdata.append("no_hp", data.no_hp);
    formdata.append("alamat", data.alamat);
    formdata.append("is_private", data.is_private);
    formdata.append("keterangan", data.keterangan);
    formdata.append("pelanggaran_id", data.pelanggaran_id.join(","));
    formdata.append("foto", data.foto[0]);

    if (data.dokumen.length > 0) {
      Array.from(data.dokumen).forEach((e) => {
        formdata.append("dokumen", e);
      });
    }

    const toastid = toast.loading("Please wait...");

    const success = await createLaporanPublic(formdata);
    if (!success) {
      swal.fire({
        title: "Data tidak berhasil dikirim",
        icon: "error",
        confirmButtonColor: "#6FB9DE",
      });
    } else {
      swal.fire({
        title: "Data berhasil dikirim",
        icon: "success",
        confirmButtonColor: "#6FB9DE",
      });
      Router.push("/laporan/new");
    }
  };

  createLaporan = async (token, kode = "") => {
    const data = this.state.data;
    const formdata = new FormData();
    formdata.append("pt_id", data.pt_id);
    formdata.append("keterangan", data.keterangan);
    formdata.append("pelanggaran_id", data.pelanggaran_id.join(","));
    if (kode) {
      formdata.append("no_verifikasi", kode);
    }
    if (data.dokumen.length > 0) {
      Array.from(data.dokumen).forEach((e) => {
        formdata.append("dokumen", e);
      });
    }

    this.setState({ loading: true });
    const success = await createLaporanPublic(token, formdata);
    if (!success) {
      swal.fire({
        title: "Kode verifikasi salah",
        icon: "error",
        confirmButtonColor: "#3e3a8e",
      });
      this.setState({ kodeVerifNotOK: true, error: false });
    } else {
      swal.fire({
        title: "Data berhasil dikirim",
        icon: "success",
        confirmButtonColor: "#3e3a8e",
      });
      this.toggleModal();
      Router.push("/laporan/new");
    }
    this.setState({ loading: false });

  };

  createUser = async (data) => {
    const formdata = new FormData();
    formdata.append("no_laporan", data.no_laporan);
    formdata.append("pt_id", data.pt_id);
    if (data.nama) formdata.append("nama", data.nama);
    if (data.email) formdata.append("email", data.email);
    formdata.append("no_hp", data.no_hp);
    if (data.alamat) formdata.append("alamat", data.alamat);
    formdata.append("is_private", data.is_private);
    if (data.foto.length > 0) formdata.append("foto", data.foto[0]);
    return await createPublicUser(formdata);
  };

  render() {
    const { selectedJenis, pelanggaran } = this.state;

    return (
      <div>
        <ToastContainer />
        <Navbar className="navbar-color" expand="md" dark>
          <NavbarBrand href="/">
            <img
              className="width-133"
              src="/static/img/Logo-Sidali.png"
              alt="App Logo"
            />
          </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>
                  <Formik
                    initialValues={{
                      nama: "",
                      no_hp: "",
                      email: "",
                      alamat: "",
                      foto: [],
                      no_laporan:
                        moment(new Date()).format("DDMM") +
                        "" +
                        Math.floor(Math.random() * 1000000),
                      pt_id: "",
                      pelanggaran_id: "",
                      keterangan: "",
                      dokumen: [],
                      setuju: false,
                      is_private: false,
                    }}
                    validationSchema={laporanSchema}
                    onSubmit={async (data) => {
                      this.toggleModal(data.no_hp);
                      this.setState({ data, no_laporan: data.no_laporan });
                      this.setState({ data, no_hp: data.no_hp });
                      const user = await this.createUser(data);
                      const token = user.data.token;
                      this.setState({ user, token });
                    }}
                  >
                    <Form className="form-horizontal">
                      <div class="header-1">
                        <h2 class="card-title-1">Identitas Pelapor</h2>
                      </div>
                      <FormGroup row></FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Nama Lengkap
                        </label>
                        <div className="col-md-10">
                          <Field name="nama">
                            {({ field }) => <Input type="text" {...field} />}
                          </Field>
                          <ErrorMessage
                            name="nama"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Nomor Aktif
                          <span> &#40;opsional&#41;</span>
                        </label>
                        <div className="col-md-10">
                          <Field name="no_hp">
                            {({ field, form }) => (
                              <Input type="tel" id="phone"
                                name="phone"
                                className="invalid-mv"
                                pattern="[0-9]{10,13}"
                                // title="Nomor telepon tidak valid"
                                {...field} />
                            )}
                          </Field>
                          <ErrorMessage
                            name="no_hp"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">Email</label>
                        <div className="col-md-10">
                          <Field name="email">
                            {({ field }) => <Input type="email" className="invalid-mv" {...field} />}
                          </Field>
                          <ErrorMessage
                            name="email"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Alamat
                        </label>
                        <div className="col-md-10">
                          <Field name="alamat">
                            {({ field }) => (
                              <Input type="textarea" {...field} />
                            )}
                          </Field>
                          <ErrorMessage
                            name="alamat"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Foto Kartu Identitas
                        </label>
                        <div className="col-md-10">
                          <Field name="foto">
                            {({ field, form }) => (
                              <Input
                                type="file"
                                onChange={(e) =>
                                  form.setFieldValue(
                                    field.name,
                                    Array.from(e.currentTarget.files)
                                  )
                                }
                              />
                            )}
                          </Field>
                          <ErrorMessage
                            name="foto"
                            component="div"
                            className="form-text text-danger"
                          />
                          <p className="mrgn-top-5">
                            Ukuran setiap dokumen maksimal 15mb
                          </p>
                        </div>
                        <div className="col-xl-10">
                          <div className="checkbox c-checkbox">
                            <label>
                              <Field name="is_private">
                                {({ field }) => (
                                  <Input type="checkbox" {...field} />
                                )}
                              </Field>
                              <span className="fa fa-check"></span>
                              <text>
                                Klik jika ingin merahasiakan identitas anda
                              </text>
                            </label>
                          </div>
                        </div>
                      </FormGroup>
                      <div class="header-1">
                        <h2 class="card-title-1">
                          Detail Laporan
                        </h2>
                      </div>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Nomor Pelaporan
                        </label>
                        <div className="col-md-10">
                          <Field name="no_laporan">
                            {({ field }) => (
                              <Input disabled type="text" {...field} />
                            )}
                          </Field>
                          <ErrorMessage
                            name="no_laporan"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Perguruan Tinggi yang Dilaporkan
                          <span className="star-color"></span>
                        </label>
                        <div className="col-md-10">
                          <Field name="pt_id">
                            {({ field, form }) => (
                              <AsyncSelect
                                cacheOptions
                                loadOptions={loadOptions}
                                defaultOptions
                                onChange={(e) => {
                                  this.handleChangeSelectPerguruanTinggi(e);
                                  form.setFieldValue(field.name, e.value);
                                }}
                                onInputChange={this.handleInputChange}
                              />
                            )}
                          </Field>
                          <ErrorMessage
                            name="pt_id"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Jenis Pelanggaran<span className="star-color"></span>
                        </label>
                        <div className="col-md-10">
                          <Field name="pelanggaran_id">
                            {({ field, form }) => (
                              <Select
                                instanceId={selectInstanceId + 1}
                                isMulti
                                value={selectedJenis}
                                onChange={(e) => {
                                  this.handleChangeSelectJenis(e);
                                  form.setFieldValue(
                                    field.name,
                                    e.map((e) => e.value)
                                  );
                                }}
                                options={
                                  pelanggaran.data
                                    ? this.optionsJenisPelanggaran(pelanggaran)
                                    : []
                                }
                                required
                              />
                            )}
                          </Field>
                          <ErrorMessage
                            name="pelanggaran_id"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          Keterangan Laporan<span className="star-color"></span>
                        </label>
                        <div className="col-md-10">
                          <Field name="keterangan">
                            {({ field }) => (
                              <Input type="textarea" {...field} />
                            )}
                          </Field>
                          <ErrorMessage
                            name="keterangan"
                            component="div"
                            className="form-text text-danger"
                          />
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <label className="col-md-2 col-form-label">
                          File Pendukung
                        </label>
                        <div className="col-md-10">
                          <Field name="dokumen">
                            {({ field, form }) => (
                              <Input
                                type="file"
                                multiple
                                onChange={(e) =>
                                  form.setFieldValue(
                                    field.name,
                                    Array.from(e.currentTarget.files)
                                  )
                                }
                              />
                            )}
                          </Field>
                          <ErrorMessage
                            name="dokumen"
                            component="div"
                            className="form-text text-danger"
                          />
                          <p className="mrgn-top-5">
                            Ukuran setiap dokumen maksimal 15mb
                          </p>
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <div className="col-xl-10">
                          <div className="checkbox c-checkbox">
                            <label>
                              <Field name="setuju">
                                {({ field }) => (
                                  <Input type="checkbox" {...field} />
                                )}
                              </Field>
                              <span className="fa fa-check"></span>
                              <text>
                                Klik jika data yang anda laporkan sudah benar
                              </text>
                              <ErrorMessage
                                name="setuju"
                                component="div"
                                className="form-text text-danger"
                              />
                            </label>
                          </div>
                        </div>
                      </FormGroup>
                      <FormGroup row>
                        <div className="posisi-btn-1 btn-radius">
                          <Button
                            className="button-kirimlaporan btn-login"
                            color
                            type="submit"
                          >
                            <h3 className="text-kirimlaporan font-color-white">
                              Kirim Laporan
                            </h3>
                          </Button>
                        </div>
                      </FormGroup>
                    </Form>
                  </Formik>
                </CardBody>
              </Card>
            </Col>
          </Row>
          <Modal isOpen={this.state.modal}>
            <form className="form-horizontal">
              <ModalBody>
                <FormGroup>
                  <div className="">
                    <label className=" font-weight-bold h6">
                      Masukkan Kode Verifikasi :
                    </label>
                    <div className="border-2">
                      <Input
                        className="border-2 "
                        invalid={this.state.error}
                        onChange={(e) =>
                          this.setState({ kode: e.target.value })
                        }
                        type="text"
                        placeholder={this.state.error}
                      />
                      <FormFeedback invalid={this.state.error}>
                        Kode verifikasi harus diisi
                      </FormFeedback>
                    </div>
                    <p>
                      *Kode verifikasi terkirim ke nomor WA {this.state.no_hp}
                    </p>
                  </div>

                  <p className="font-color-black">
                    NOTE : Diharapkan pelapor dapat mencatat ataupun mengingat
                    nomor laporan di bawah ini untuk mempermudah proses
                    selanjutnya.
                  </p>
                  <div className="modals">
                    <label className="modals  text-white font-20 ">
                      Nomor Laporan : {this.state.no_laporan}
                    </label>
                    <CopyToClipboard
                      text={this.state.no_laporan}
                      options={{ asHtml: true }}
                    >
                      <Button color className="btn-verif">
                        <img
                          src="/static/img/icon-copy.png"
                          alt="icon-copy"
                          width="20"
                        />
                      </Button>
                    </CopyToClipboard>
                  </div>
                  {/* {this.state.error && (
                    <div className="form-text text-danger">
                      {this.state.error}
                    </div>
                  )} */}
                </FormGroup>
              </ModalBody>
              <ModalFooter>

                <Button
                  className=" float-lg-left mr-auto btn-login"
                  color
                  disabled={this.state.disablekirim3}
                  onClick={async () => {
                    this.setState({ disablekirim2: true, disablecancel: true, loading2: true })
                    await this.createLaporan(this.state.token);
                    this.setState({ disablekirim2: false, disablecancel: false, loading2: false })

                  }}
                >
                  {this.state.loading2 ?
                    (
                      <div class="d-flex justify-content-center">
                        <span
                          class="spinner-border spinner-border-sm text-white"
                          role="status"
                        ></span>
                        <span className="font-color-white">
                          &nbsp; Diproses...
                        </span>
                      </div>
                    ) : (
                      <span className="font-color-white">
                        Buat Laporan Tanpa Kode Verifikasi
                      </span>
                    )}
                </Button>
                <Button
                  className="bg-danger"
                  color
                  disabled={this.state.disablecancel}
                  onClick={() => this.setState({ modal: false })}
                >
                  <span className="font-color-white">Cancel</span>
                </Button>
                <Button
                  className="bg-success float-lg-right"
                  color
                  disabled={this.state.disablekirim2}
                  onClick={async () => {
                    this.setState({ disablekirim3: true, disablecancel: true })
                    if (this.state.kode) {
                      await this.createLaporan(
                        this.state.token,
                        this.state.kode
                      );
                    } else {
                      this.setState({ error: true, error: "Harus diisi" });
                    }
                    this.setState({ disablekirim3: false, disablecancel: false })
                  }}
                >
                  <span className="font-color-white">Kirim</span>
                </Button>
              </ModalFooter>
            </form>
          </Modal>

          <Modal isOpen={this.state.modalNotnoHP}>
            <form className="form-horizontal">
              <ModalBody>
                <FormGroup>
                  <p className="font-color-black">
                    NOTE : Diharapkan pelapor dapat mencatat ataupun mengingat
                    nomor laporan di bawah ini untuk mempermudah proses
                    selanjutnya.
                  </p>
                  <div className="modals">
                    <label className="modals font-color-white font-20 ">
                      Nomor Laporan : {this.state.no_laporan}
                    </label>
                    <CopyToClipboard
                      text={this.state.no_laporan}
                      options={{ asHtml: true }}
                    >
                      <Button color className="btn-verif">
                        <img
                          src="/static/img/icon-copy.png"
                          alt="icon-copy"
                          width="20"
                        />
                      </Button>
                    </CopyToClipboard>
                  </div>
                  {this.state.error && (
                    <div className="form-text text-danger">
                      {this.state.error}
                    </div>
                  )}
                </FormGroup>
              </ModalBody>
              <ModalFooter>
                <Button
                  className="bg-danger"
                  color
                  disabled={this.state.disablecancel}
                  // disabled={true}
                  onClick={() => this.setState({ modalNotnoHP: false })}
                >
                  <span className="font-color-white">Cancel</span>
                </Button>
                <Button
                  className="btn-login bg-success"
                  color
                  disabled={this.state.disablekirim}
                  onClick={async () => {
                    this.setState({ disablecancel: true })
                    await this.createLaporan(this.state.token);
                    this.setState({ disablecancel: false })

                  }}
                >
                  <span className="font-color-white">
                    Kirim
                  </span>
                </Button>
              </ModalFooter>
            </form>
          </Modal>
        </ContentWrapper>
      </div >
    );
  }
}

App.Layout = BasePage;

export default App;
