import React, { PureComponent } from "react";
import { Link } from "react-router-dom";

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 "./profile.scss";
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: "",
      formData: {
        title: "",
        quantity: "",
        weight: "",
        unit: "",
        sequence: "",
      },
      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,
    };
  }

  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");
    //alert(admin_id);
    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'];
    //get info by admin id in controller
    fetch(myConstClass.BASE_URL + "user/getProfileInfo/" + admin_id)
      .then((response) => response.json())
      .then((response) => {
        this.setState({ formData: 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");
    //  alert (admin_id);
    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 + `user/edit_admin2/` + admin_id, {
        method: "POST",
        body: data,
        // body: JSON.stringify($('#pform').serializeArray()),
      })
        .then((response) => response.json())
        .then((response) => {
          if (response == true) {
            this.state.user_id == "0"
              ? toastr.success(
                  "Success",
                  "Profile Details Successfully..!",
                  this.options
                )
              : toastr.success(
                  "Success",
                  "Profile Details Updated Successfully..!",
                  this.options
                );

            this.props.history.push("/dashboard");
          } else {
            toastr.error(
              "Error",
              "Can  not Update Profile Details..!",
              this.options
            );
          }
        })
        .catch();
    });
  };

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

  render() {
    const { formData, units, submitted } = this.state;
    const { organization } = this.state;
    let { imagePreviewUrl } = this.state;
    let $imagePreview = null;
    let file_link;
    let img;
    var admin_id = localStorage.getItem("uname");
    let profile_img;

    if (formData.image == "" || formData.image == null) {
    } else {
      file_link =
        `http://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" }} />;
    }

    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" : "Edit"}
          </HeaderTitle>

          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">Dashboard</Link>
            </BreadcrumbItem>

            <BreadcrumbItem active>
              {this.state.user_id !== "0" ? "Edit" : "Edit"}
            </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>
                    <Label for="example">First Name</Label>
                    <AvInput
                      name="first_name"
                      id="example"
                      required
                      value={formData ? formData.first_name : ""}
                    />
                    <AvFeedback>Enter First Name!</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Last Name</Label>
                    <AvInput
                      name="last_name"
                      id="example"
                      required
                      value={formData ? formData.last_name : ""}
                    />
                    <AvFeedback>Enter Last Name!</AvFeedback>
                  </AvGroup>
                </Col>
              </Row>
              <Row>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Email</Label>
                    <AvInput
                      name="email"
                      type="email"
                      disabled
                      id="example"
                      required
                      value={formData ? formData.email : ""}
                    />
                    <AvFeedback>Enter Email</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Password</Label>
                    <AvInput
                      name="password"
                      id="example"
                      required
                      value={formData ? formData.password : ""}
                    />
                    <AvFeedback>Enter Password</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Mobile No</Label>
                    <AvInput
                      name="mobile_no"
                      id="example"
                      required
                      value={formData ? formData.mobile_no : ""}
                    />
                    <AvFeedback>Enter Mobile No</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Position</Label>
                    <AvInput
                      name="position"
                      id="example"
                      required
                      value={formData ? formData.position : ""}
                    />
                    <AvFeedback>Enter Position</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <AvField
                      type="select"
                      name="gender"
                      label="Select Gender"
                      value={formData ? formData.gender : ""}
                    >
                      <option value="1">Male</option>
                      <option value="2">Female</option>
                      <option value="3">Other</option>
                    </AvField>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  {/* <AvGroup>
                <Label for="example">Status</Label>
                <Input
                        type="select"
                        id="exampleCustomSelect"
                        name="status"
                        className="mb-3"
                    >
                        <option value="1">Active</option>
                        <option value="2">In-Active</option>
                    </Input>
                </AvGroup> */}
                  <AvGroup>
                    <AvField
                      type="select"
                      name="status"
                      label="Select Status"
                      value={formData ? formData.status : ""}
                    >
                      <option value="1">Active</option>
                      <option value="2">In-Active</option>
                    </AvField>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <Label for="example">Select Image</Label>
                  <Input
                    type="file"
                    name="image"
                    id="file"
                    onChange={(e) => this._handleImageChange(e)}
                  />
                  <br /> <br />
                  {img}
                  <br /> <br />
                  <div className="imgPreview">{$imagePreview}</div>
                  <br />
                </Col>
                <br />
                <br />
                <br />
                {/* <Col lg={6}>
                 <AvField
                  type="select"
                  name="unit"
                  label="Unit"
                  value={formData ? formData.unit:''}
                >
                  {units ?  units.map((cell, i) => {
                  return(<option value={cell.id}>{cell.name}({cell.symbol})</option>)
                  }) : ''}       
                </AvField>
                </Col> */}
              </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="/dashboard"
                  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;
