import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import "react-datepicker/dist/react-datepicker.css";
import {
  Breadcrumb,
  BreadcrumbItem,
  Row,
  Col,
  Card,
  CardBody,
  Container,
  Button,
  Label,
  FormGroup,
} 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 {
  AvForm,
  AvGroup,
  AvInput,
  AvFeedback,
} from "availity-reactstrap-validation";

import { T, Config, TF } from "react-translator-component";
Config.default = localStorage.getItem("lang");

class Validation extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    // state = {
    //   startDate: new Date()
    // };
    this.state = {
      user_id: "0",
      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() {
    var admin_id = localStorage.getItem("uname");
    if (admin_id == null) {
      this.routeChange();
    }
    const answer_array = this.props.location.pathname.split("/");
    //alert(this.props.location.state._id);
    if (answer_array) {
      //this.state.user_id = answer_array['5'];
      this.state.user_id = this.props.location.state._id;
      fetch(
        myConstClass.BASE_URL +
          "user/getTicketCategoryInfo/" +
          this.state.user_id
      )
        .then((response) => response.json())
        .then((response) => {
          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }
  }

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

    this.setState({ submitted: true }, () => {
      //setTimeout(() => this.setState({ submitted: false }), 5000);
      const data = new FormData();
      // data.append('announcemnt',html);
      data.append("formdata", JSON.stringify($("#pform").serializeArray()));
      fetch(
        myConstClass.BASE_URL +
          `user/add_ticket_category/` +
          admin_id +
          "/" +
          this.state.user_id,
        {
          method: "POST",
          body: data,
          // contentType: "application/json; charset=utf-8",
        }
      )
        .then((response) => response.json())
        .then((response) => {
          this.setState({ submitted: false });
          if (response == true) {
            this.state.user_id == "0"
              ? toastr.success(
                  TF("{0}", T("Success")),
                  TF("{0}...!", T(myConstClass.ADDMSG)),
                  this.options
                )
              : toastr.success(
                  TF("{0}", T("Success")),
                  TF("{0}.!", T(myConstClass.UPDATEMSG)),
                  this.options
                );

            this.props.history.push(
              "/" +
               
                "settingsticketcategory/listing"
            );
          } else {
            toastr.error(
              TF("{0}", T("Error")),
              TF("{0}.!", T(myConstClass.ERRORMSG)),
              this.options
            );
          }
        })
        .catch();
    });
  };

  render() {
    const { formData, submitted } = this.state;

    return (
      <Container fluid>
        <Header>
          <HeaderTitle>
            {this.state.user_id != "0" ? T("Edit") : T("Add")}
          </HeaderTitle>
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">{T("Dashboard")}</Link>
            </BreadcrumbItem>
            <BreadcrumbItem>
              <Link
                to={
                  "/" +
                 
                  "settingsticketcategory/listing"
                }
              >
                {" "}
                {T("Ticket")} {T("Category")} 
              </Link>
            </BreadcrumbItem>
            <BreadcrumbItem active>
              {this.state.user_id != "0" ? T("Edit") : T("Add")}
            </BreadcrumbItem>
          </Breadcrumb>
        </Header>
        <Card>
          <CardBody>
            <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
              <h4>
                {T("Ticket")} {T("Category")}
                <span
                  style={{ color: "red", fontSize: "14px", float: "right" }}
                >
                  {" "}
                  {T("All fields marked with * are required")}{" "}
                </span>
              </h4>
              <hr />
              <Row>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">
                      {" "}
                      {T("Ticket")} {T("Category")} {T("Name")}{" "}
                    </Label>
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="type"
                      id="example"
                      required
                      value={formData ? formData.type : ""}
                    />
                    <AvFeedback>
                      {" "}
                      {TF("{0} {1} {2} {3}", T("Enter"), T("Ticket"), T("Category"), T("Name"))}!
                    </AvFeedback>
                  </AvGroup>
                </Col>

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

              <FormGroup>
                <Link
                  to={
                    "/" +
                    
                    "settingsticketcategory/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",
                  }}
                >
                  {T("Cancel")}
                </Link>
                {this.state.user_id != "0" ? (
                  <Button disabled={submitted}>
                    {(submitted &&
                      TF(
                        "{0} {1} {2} {3}!",
                        T("Your"),
                        T("form"),
                        T("is"),
                        T("submitted")
                      )) ||
                      (!submitted && T("Update"))}
                  </Button>
                ) : (
                  <Button disabled={submitted}>
                    {(submitted &&
                      TF(
                        "{0} {1} {2} {3}!",
                        T("Your"),
                        T("form"),
                        T("is"),
                        T("submitted")
                      )) ||
                      (!submitted && T("Add"))}
                  </Button>
                )}
              </FormGroup>
            </AvForm>
          </CardBody>
        </Card>
      </Container>
    );
  }
}
export default Validation;
