import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import InputMask from "react-input-mask";
import DatePicker from "react-datepicker";
import TimePicker from "react-time-picker";
import "react-datepicker/dist/react-datepicker.css";
import ReactQuill from "react-quill";
import {
  Breadcrumb,
  BreadcrumbItem,
  Row,
  Col,
  Card,
  Input,
  CardBody,
  CardHeader,
  CardTitle,
  Container,
  Button,
  Label,
  FormGroup,
  CustomInput,
} from "reactstrap";

import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";

import * as myConstClass from "../../constant.js";
import $ from "jquery";
import { toastr } from "react-redux-toastr";
import * as Icon from "react-feather";
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox,
} from "availity-reactstrap-validation";

class Validation extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    // this.googleTranslateElementInit =
    //   this.googleTranslateElementInit.bind(this);
    this.state = { file: "" };
    this.state = { file: "", imagePreviewUrl: "" };
    this.state = {
      user_id: "0",
      units: "",
      org: "",
      emp: "",
      startDate: new Date(),
      time: "10:00",
      timezones: "",
      formData: {
        employee_id: "",
        attendance_date: "",
        clock_in: "",
        clock_out: "",
        timezone: "",
      },
      submitted: false,
      timeOut: 5000,
      showCloseButton: true,
      progressBar: true,
      position: "top-right",
    };

    this.options = {
      timeOut: parseInt(this.state.timeOut),
      showCloseButton: this.state.showCloseButton,
      progressBar: this.state.progressBar,
      position: this.state.position,
    };
  }

  // _handleImageChange(e) {
  //     e.preventDefault();
  //     let reader = new FileReader();
  //     let file = e.target.files[0];
  //     reader.onloadend = () => {
  //       this.setState({
  //         file: file,
  //         imagePreviewUrl: reader.result
  //       });
  //     }
  //     reader.readAsDataURL(file)
  //   }
  _handleImageChange(e) {
    e.preventDefault();
    let file = e.target.files[0];
    let reader = new FileReader();
    if (file != undefined) {
      reader.readAsDataURL(file);
    }

    reader.onloadend = () => {
      var image = new Image();
      image.src = reader.result;
      image.onload = () => {
        var height = image.height;
        var width = image.width;
        //alert(height);alert(width);
        if (height != 300 || width != 600) {
          alert("Uploaded image has not valid Height and Width");
          $("#file").val(null);
          this.setState({
            file: "",
            imagePreviewUrl: "",
          });
          return false;
        } else {
          this.setState({
            file: file,
            imagePreviewUrl: reader.result,
          });
        }
      };
    };
    //reader.readAsDataURL(file)
  }
  routeChange() {
    this.props.history.push("/");
  }
  componentDidMount() {
    // window.googleTranslateElementInit = this.googleTranslateElementInit;
    // const google = window.google;
    // const script = document.createElement("script");
    // script.src =
    //   "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    // script.async = true;
    // document.body.appendChild(script);

    var admin_id = localStorage.getItem("uname");
    if (admin_id == null) {
      this.routeChange();
    }
    const answer_array = this.props.location.pathname.split("/");
    //alert(answer_array['3']);
    if (answer_array["3"]) {
      this.state.user_id = answer_array["3"];
      fetch(
        myConstClass.BASE_URL + "organization/getAdInfo/" + answer_array["3"]
      )
        .then((response) => response.json())
        .then((response) => {
          if (response.image) {
            var file_link =
              `https://beta.workzoneplus.com/backend/uploads/banners/` +
              response.image;
            this.setState({ imagePreviewUrl: file_link });
          }

          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }

    fetch(
      myConstClass.BASE_URL + "organization/get_all_organizations/" + admin_id
    )
      .then((response) => response.json())
      .then((response) => {
        this.setState({ organization: response });
      })
      .catch((err) => console.log(err));
  }

  // googleTranslateElementInit() {
  //   // / eslint-disable no-new /
  //   const google = window.google;
  //   new google.translate.TranslateElement(
  //     { pageLanguage: "en" },
  //     "google_translate_element_1"
  //   );
  //   new window.google.translate.TranslateElement(
  //     {
  //       pageLanguage: "pt",
  //       layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT,
  //     },
  //     "google_translate_element_1"
  //   );
  // }

  handleValidSubmit = () => {
    var admin_id = localStorage.getItem("uname");

    this.setState({ submitted: true }, () => {
      setTimeout(() => this.setState({ submitted: false }), 5000);
      const data = new FormData();
      data.append("file", this.state.file);
      data.append("formdata", JSON.stringify($("#pform").serializeArray()));
      fetch(
        myConstClass.BASE_URL +
          `organization/add_ads/` +
          admin_id +
          "/" +
          this.state.user_id,
        {
          method: "POST",
          body: data,
          // contentType: "application/json; charset=utf-8",
        }
      )
        .then((response) => response.json())
        .then((response) => {
          if (response == true) {
            this.state.user_id == "0"
              ? toastr.success(
                  "Success",
                  "Adverts  Added Successfully..!",
                  this.options
                )
              : toastr.success(
                  "Success",
                  "Adverts  Updated Successfully..!",
                  this.options
                );

            this.props.history.push("/promotions/listing");
          } else {
            toastr.error("Error", "Can not Add Adverts  ..!", this.options);
          }
        })
        .catch();
    });
  };
  handleFromDateChange = (from_date) => {
    this.setState({ from_date });
    if (from_date) {
      $("#spanfmdatebox").removeClass("is-invalid1");
      $("#spanfmdatelabel").css("color", "#3e4676");
      $("#spanfmdatebox").css("border-color", "hsl(0,0%,80%)");
      $("#spanfmdate").hide();
    } else {
      $("#spanfmdatebox").addClass("is-invalid1");
      $("#spanfmdatelabel").css("color", "#dc3545");
      $("#spanfmdatebox").css("border-color", "#dc3545");
      $("#spanfmdate").show();
    }
  };
  handleToDateChange = (to_date) => {
    this.setState({ to_date });
    if (to_date) {
      $("#spantodatebox").removeClass("is-invalid1");
      $("#spantodatelabel").css("color", "#3e4676");
      $("#spantodatebox").css("border-color", "hsl(0,0%,80%)");
      $("#spantodate").hide();
    } else {
      $("#spantodatebox").addClass("is-invalid1");
      $("#spantodatelabel").css("color", "#dc3545");
      $("#spantodatebox").css("border-color", "#dc3545");
      $("#spantodate").show();
    }
  };
  render() {
    const { formData, units, submitted } = this.state;
    const { organization } = this.state;
    let { imagePreviewUrl } = this.state;
    let $imagePreview = null;
    let file_link;
    let img;
    if (this.state.user_id !== "0") {
      //  file_link = `https://alpha.workzoneplus.com/backend/uploads/banners/`+formData.image;
      file_link =
        `https://beta.workzoneplus.com/backend/uploads/banners/` +
        formData.image;
      // file_link = `http://localhost/workzone/backend/uploads/banners/`+formData.image;
      img = <img src={file_link} style={{ width: "50px", height: "50px" }} />;
    } else {
      file_link = "";
      img = "";
    }

    if (imagePreviewUrl) {
      $imagePreview = (
        <img src={imagePreviewUrl} style={{ width: "50px", height: "50px" }} />
      );
      img = "";
    } else {
      $imagePreview = <div className="previewText"></div>;
    }

    return (
      <Container fluid>
        <Header>
          {/* <div id="google_translate_element_1"></div> */}
          <br />
          <HeaderTitle>
            {this.state.user_id !== "0" ? "Edit" : "Add"}
          </HeaderTitle>
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">Dashboard</Link>
            </BreadcrumbItem>
            <BreadcrumbItem>
              <Link to="/promotions/listing">Adverts List</Link>
            </BreadcrumbItem>
            <BreadcrumbItem active>
              {this.state.user_id !== "0" ? "Edit" : "Add"}
            </BreadcrumbItem>
          </Breadcrumb>
        </Header>
        <Card>
          {/* <CardHeader>
              <CardTitle tag="h5">Availity Validation</CardTitle>
              <h6 className="card-subtitle text-muted">
                Form validation by availity-reactstrap-validation
              </h6>
            </CardHeader> */}
          <CardBody>
            <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
              {/* With AvGroup AvInput and AvFeedback to build your own */}
              <Row>
                <Col lg={6}>
                  <AvGroup>
                    {/* <AvInput name="employee_id" id="example" required value={formData ? formData.employee_id:''}/>
                  <AvFeedback>Enter Employee ID!</AvFeedback> */}
                    <AvField
                      type="select"
                      name="organization_id"
                      label="Select Organization"
                      value={formData ? formData.organization_id : ""}
                    >
                      <option value="0">All</option>
                      {organization
                        ? organization.map((cell, i) => {
                            return (
                              <option value={cell.id}>{cell.title}</option>
                            );
                          })
                        : ""}
                    </AvField>
                  </AvGroup>
                </Col>

                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Sequence No</Label>
                    <span style={{ color: "red", fontSize: "15px" }}>
                      {" "}
                      *
                    </span>{" "}
                    <AvInput
                      type="number"
                      name="sequence_no"
                      validate={{ min: { value: 1 } }}
                      id="example"
                      required
                      value={formData ? formData.sequence_no : ""}
                    />
                    <AvFeedback>
                      Enter Sequence No and it must be at least 1..!
                    </AvFeedback>
                  </AvGroup>
                </Col>
              </Row>

              <Row>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Title</Label>
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="name"
                      id="example"
                      required
                      value={formData ? formData.name : ""}
                    />
                    <AvFeedback>Enter Name</AvFeedback>
                  </AvGroup>
                </Col>

                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Description</Label>
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      type="textarea"
                      name="descripation"
                      id="example"
                      required
                      value={formData ? formData.descripation : ""}
                    />
                    <AvFeedback>Enter Description</AvFeedback>
                  </AvGroup>
                </Col>
              </Row>

              <Row>
                <Col lg={6}>
                  {/* <AvGroup> */}
                  <Label id="spanfmdatelabel" for="example">
                    From Date (DD/MM/YYYY)
                  </Label>
                  <br />
                  {this.state.user_id != "0" ? (
                    <DatePicker
                      name="from_date"
                      required
                      selected={this.state.from_date}
                      onChange={this.handleFromDateChange}
                      dateFormat="dd-MM-yyyy"
                      className="form-control is-untouched is-pristine av-valid"
                      style={{ width: "352px", height: "32px" }}
                      // value={formData ? formData.from_date:this.state.from_date}
                      autoComplete="off"
                      value={this.state.from_date || formData.from_date}
                      id="spanfmdatebox"
                    />
                  ) : (
                    <DatePicker
                      name="from_date"
                      required
                      selected={this.state.from_date}
                      className="form-control is-untouched is-pristine av-valid"
                      onChange={this.handleFromDateChange}
                      dateFormat="dd-MM-yyyy"
                      autoComplete="off"
                      value={this.state.from_date}
                      id="spanfmdatebox"
                    />
                  )}
                  <span
                    id="spanfmdate"
                    style={{ color: "red" }}
                    //style={this.state.showGalleryPlayButton}
                    style={{ display: "none" }}
                    class="invalid-feedback11"
                  >
                    {" "}
                    Enter From Date
                  </span>
                </Col>

                <Col lg={6}>
                  <Label id="spantodatelabel" for="example">
                    To Date (DD/MM/YYYY")
                  </Label>
                  <br />
                  {this.state.user_id != "0" ? (
                    <DatePicker
                      name="to_date"
                      required
                      selected={this.state.to_date}
                      minDate={this.state.from_date ? this.state.from_date : ""}
                      onChange={this.handleToDateChange}
                      dateFormat="dd-MM-yyyy"
                      className="form-control is-untouched is-pristine av-valid"
                      style={{ width: "352px", height: "32px" }}
                      // value={formData ? formData.to_date:this.state.to_date}
                      // value={this.state.to_date || formData.to_date}
                      autoComplete="off"
                      value={this.state.to_date || formData.to_date}
                      id="spantodatebox"
                    />
                  ) : (
                    <DatePicker
                      name="to_date"
                      required
                      selected={this.state.to_date}
                      class="re_date"
                      className="form-control is-untouched is-pristine av-valid"
                      minDate={this.state.from_date ? this.state.from_date : ""}
                      onChange={this.handleToDateChange}
                      dateFormat="dd-MM-yyyy"
                      autoComplete="off"
                      value={this.state.to_date}
                      id="spantodatebox"
                    />
                  )}

                  <span
                    id="spantodate"
                    style={{ color: "red" }}
                    //style={this.state.showGalleryPlayButton}
                    style={{ display: "none" }}
                    class="invalid-feedback11"
                  >
                    Enter To Date
                  </span>
                </Col>
              </Row>

              <br />

              <Row>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Redirect URL</Label>
                    <span style={{ color: "red", fontSize: "15px" }}>
                      {" "}
                      *
                    </span>{" "}
                    <AvInput
                      name="redirect_url"
                      id="example"
                      type="url"
                      required
                      value={formData ? formData.redirect_url : ""}
                    />
                    <AvFeedback>Enter Redirect URL..!</AvFeedback>
                  </AvGroup>
                </Col>

                <Col lg={6}>
                <Label for="example">Select Status</Label>{" "}
                  <AvGroup>
                    <AvField
                      //style={(this.state.reserved == '1') ? {pointerEvents:'none'}:{pointerEvents:'cursor'}}
                      type="select"
                      name="status"
                      // readOnly={(this.state.reserved == '1') ? 'disabled' : false}
                      value={formData ? formData.status : "1"}
                      // onChange={this.ochangealcodeactive}
                      // value={this.state.organization_id}
                    >
                      <option value="1">Active</option>
                      <option value="2">In-Active</option>
                    </AvField>
                  </AvGroup>
                </Col>
              </Row>
              <Row>
                <Col lg={6}>
                  <Label for="example">Select Image</Label>{" "}
                  <span style={{ color: "red", fontSize: "15px" }}> *</span>{" "}
                  <Input
                    type="file"
                    name="image"
                    id="file"
                    onChange={(e) => this._handleImageChange(e)}
                  />
                  <small>Image Size: 600 X 300 px</small>
                  <br></br>
                  <small>('png','jpg','jpeg','JPG')</small>
                  <br />
                  {/* {img} */}
                  <br /> <br />
                  <div className="imgPreview">{$imagePreview}</div>
                </Col>
                {this.state.user_id != "0" ? (
                  <Col lg={6}>
                    <Label for="example">Advert No.</Label>
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="advert_no"
                      id="example"
                      readOnly={true}
                      value={formData ? formData.advert_no : ""}
                    />
                  </Col>
                ) : (
                  ""
                )}
                <br />
                <br />
                <br />
                <br />
              </Row>
              <br />
              {/* <Row>
                  <Col lg={6}>
                <AvGroup>
                  <Label for="example">Sequence</Label>
                  <AvInput name="sequence" value={formData ? formData.sequence:''} id="example" validate={{
                  required: {value: true},
                  pattern: {value: '^[0-9]+$'},
                  
                }} />
                  <AvFeedback>Enter Number</AvFeedback>
                </AvGroup>
                </Col>
                </Row> */}

              <FormGroup>
                <Link
                  to="/promotions/listing"
                  style={{
                    margin: "0rem 1.50rem 1.50rem 0rem",
                    border: "#6f42c1 1px solid",
                    color: "#6f42c1",
                    padding: "0.10rem 0.90rem 0.30rem 0.90rem",
                    textDecoration: "none",
                    borderRadius: "0.2rem",
                  }}
                >
                  Cancel
                </Link>
                {this.state.user_id != "0" ? (
                  <Button disabled={submitted}>
                    {(submitted && "Your form is submitted!") ||
                      (!submitted && "Update")}
                  </Button>
                ) : (
                  <Button disabled={submitted}>
                    {(submitted && "Your form is submitted!") ||
                      (!submitted && "Add")}
                  </Button>
                )}
              </FormGroup>
            </AvForm>
          </CardBody>
        </Card>
      </Container>
    );
  }
}
export default Validation;
