import React, { Component } from 'react';
import withRouter from "../../Utils/withRouter";
import axios from "axios";
import Swal from "sweetalert2";
import PageTitle from "../../Components/PageTitle";
import { ConfigContext } from "../../Context/ConfigContext";
import { IsRequired } from '../../Components/InputElements';
import { NavLink } from 'react-router-dom';

class CreateCompany extends Component {
  static contextType = ConfigContext;
  constructor(props) {
    super(props);
    this.state = {
      postLoading: false,
      company_id: 0,
      company_code: "",
      company_name: "",
      email: "",
      mobile_no: "",
      contact_person: "",
      address: "",
      service_offer: "ABStart",
      register_office_address: "",
      register_office_location: "",
      registration_number: "",
      nature_of_business: "",
      date_of_establishment: "",
      contract_start_date: "",
      contract_end_date: "",
      type_of_company: "",
      total_employees: "",
      pincode: "",
      state: "",
      country: "",
      twitter_handler: "",
      pt_applicable: 0,
      lwf_applicable: 0,
      company_logo: null,
      company_logo_url: null,
      errors: {},
    };
    this.closeRef = React.createRef();
  }

  componentDidMount() {
    const companyId = this.props.params.company_id;
    if (companyId !== 0 && companyId) {
      this.setState({ loadingList: true, company_id: companyId });
      this.GetInfo(this.props.params.company_id);
    } else {
      this.resetForm();
    }
  }


  GetInfo = (id) => {
    const { apiURL, apiHeaderJson } = this.context;
    const headers = apiHeaderJson;
    axios.get(`${apiURL}Companies/GetCompanyInfo?company_id=${id}`, { headers }).then((response) => {
      const { data, success } = response.data;
      if (success === true && data.length > 0) {
        this.setState(
          {
            company_code: data[0].company_code,
            company_logo: data[0].company_logo,
            company_logo_url: data[0].company_logo_url,
            company_name: data[0].company_name,
            email: data[0].email_address,
            mobile_no: data[0].mobile_number,
            contact_person: data[0].contact_person,
            address: data[0].company_address,
            service_offer: data[0].service_offer,
            register_office_address: data[0].registered_office_address,
            register_office_location: data[0].registered_office_location,
            registration_number: data[0].registration_number,
            nature_of_business: data[0].nature_of_business,
            date_of_establishment: data[0].date_of_establishment,
            contract_start_date: data[0].contract_start_date,
            contract_end_date: data[0].contract_end_date,
            type_of_company: data[0].type_of_company,
            total_employees: data[0].total_employees,
            pincode: data[0].pin_code,
            state: data[0].company_state,
            country: data[0].company_country,
            twitter_handler: data[0].twitter_handle,
            pt_applicable: data[0].is_pt_applicable,
            lwf_applicable: data[0].is_lwf_applicable,
          }
        )
      }
    });
  }


  handleSubmit = (e) => {
    e.preventDefault();
    const errors = this.validateForm();

    if (Object.keys(errors).length > 0) {
      this.setState({ errors });
      return;
    }

    const { apiURL, apiHeaderFile } = this.context;
    const headers = apiHeaderFile;

    this.setState({ postLoading: true, })
    var formData = {
      company_code: this.state.company_code,
      company_name: this.state.company_name,
      email_address: this.state.email,
      mobile_number: this.state.mobile_no,
      contact_person: this.state.contact_person,
      company_address: this.state.address,
      service_offer: this.state.service_offer,
      registered_office_address: this.state.register_office_address,
      registered_office_location: this.state.register_office_location,
      registration_number: this.state.registration_number,
      nature_of_business: this.state.nature_of_business,
      date_of_establishment: this.state.date_of_establishment,
      contract_start_date: this.state.contract_start_date,
      contract_end_date: this.state.contract_end_date,
      type_of_company: this.state.type_of_company,
      total_employees: this.state.total_employees,
      pin_code: this.state.pincode,
      company_state: this.state.state,
      company_country: this.state.country,
      twitter_handle: this.state.twitter_handler,
      is_pt_applicable: this.state.pt_applicable,
      is_lwf_applicable: this.state.lwf_applicable,
      company_logo: this.state.company_logo,
    }

    if (this.props.params.company_id !== 0) {
      formData.company_id = this.props.params.company_id;
    }

    axios.post(`${apiURL}Companies/CreateCompany`, formData, { headers }).then((response) => {
      const { success } = response.data;
      if (success === true) {
        this.resetForm();
        setTimeout(() => {
          if (this.props.params.company_id) {
            this.closeRef.current.click();
          }
        }, 1000);
        this.setState({ postLoading: false });
        Swal.fire({
          title: `<strong>${response.data.success === true ? 'Success' : 'Failed'}</strong>`,
          text: response.data.message,
          icon: response.data.success === true ? 'success' : 'error',
          timer: 2000,
          timerProgressBar: true,
          showConfirmButton: false,
        })
      } else {
        this.setState({ postLoading: false });
        Swal.fire({
          title: `<strong>${response.data.success === true ? 'Success' : 'Failed'}</strong>`,
          text: response.data.message,
          icon: response.data.success === true ? 'success' : 'error',
          timer: 2000,
          timerProgressBar: true,
          showConfirmButton: false,
        });
      }

    })
  };

  resetForm = () => {
    this.setState({
      postLoading: false,
      company_code: "",
      company_name: "",
      email: "",
      mobile_no: "",
      contact_person: "",
      address: "",
      service_offer: "ABStart",
      register_office_address: "",
      register_office_location: "",
      registration_number: "",
      nature_of_business: "",
      date_of_establishment: "",
      contract_start_date: "",
      contract_end_date: "",
      type_of_company: "",
      total_employees: "",
      pincode: "",
      state: "",
      country: "",
      twitter_handler: "",
      pt_applicable: 0,
      lwf_applicable: 0,
      company_logo: null,
      errors: {}
    });
  };


  handleCheckboxChange = (e) => {
    const { name, checked } = e.target;
    this.setState({
      [name]: checked ? 1 : 0
    });
  };

  // handleInputChange = (e) => {
  //   const { name, value } = e.target;
  //   this.setState((prevState) => ({
  //     [name]: value,
  //     errors: {
  //       ...prevState.errors,
  //       [name]: '',
  //     },
  //   }));
  // };

  handleInputChange = (e) => {
    const { name, value, type } = e.target;
    const newValue = type === 'file' ? e.target.files[0] : value;
    this.setState((prevState) => ({
      [name]: newValue,
      errors: {
        ...prevState.errors,
        [name]: '',
      },
    }));
  };
  ViewLogo = () => {
    Swal.fire({
      title: 'Company Logo',
      html: `<img src='${this.state.company_logo_url}' style="max-width: 100%;" />`,
      showCloseButton: true,
      showCancelButton: false,
      showConfirmButton: false,
    });
  };

  validateForm = () => {
    const errors = {};

    if (!this.state.company_code) {
      errors.company_code = 'Company Code is required';
    }

    if (!this.state.company_name) {
      errors.company_name = 'Company Name is required';
    }

    if (!this.state.company_logo) {
      errors.company_logo = 'company logo is required';
    }
    if (this.state.company_logo && this.state.company_logo.size > 10 * 1024 * 1024) {
      errors.company_logo = 'File size exceeds the maximum limit of 10MB';
    }

    if (!this.state.email) {
      errors.email = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(this.state.email)) {
      errors.email = 'Email is invalid';
    }

    if (!this.state.mobile_no) {
      errors.mobile_no = 'Mobile No. is required';
    }

    if (!this.state.contact_person) {
      errors.contact_person = 'Contact Person is required';
    }

    if (!this.state.address) {
      errors.address = 'Address is required';
    }

    if (!this.state.service_offer) {
      errors.service_offer = 'Service Offer is required';
    }

    if (!this.state.register_office_address) {
      errors.register_office_address = 'Register Office Address is required';
    }

    // if (!this.state.register_office_location) {
    //   errors.register_office_location = 'Register Office Location is required';
    // }

    // if (!this.state.registration_number) {
    //   errors.registration_number = 'Registration Number is required';
    // }

    if (!this.state.nature_of_business) {
      errors.nature_of_business = 'Nature Of Business is required';
    }

    if (!this.state.date_of_establishment) {
      errors.date_of_establishment = 'Date Of Establishment is required';
    }

    if (!this.state.contract_start_date) {
      errors.contract_start_date = 'Contract Start Date is required';
    }

    // if (!this.state.contract_end_date) {
    //   errors.contract_end_date = 'Contract End Date is required';
    // }

    if (!this.state.type_of_company) {
      errors.type_of_company = 'Type of Company is required';
    }

    if (!this.state.total_employees) {
      errors.total_employees = 'Total Employees is required';
    }

    if (!this.state.pincode) {
      errors.pincode = 'Pincode is required';
    }

    // if (!this.state.state) {
    //   errors.state = 'State is required';
    // }

    if (!this.state.country) {
      errors.country = 'Country is required';
    }

    // if (!this.state.twitter_handler) {
    //   errors.twitter_handler = 'Twitter Handler is required';
    // }

    return errors;
  };

  render() {
    const { errors } = this.state;

    return (
      <div className="main-content">
        <div className="page-content">
          <div className="container-fluid">
            <br />
            <PageTitle title={`Create Company`} primary={`Home`} />
            <div className="row">
              <div className="col-md-12">
                <div className="card">
                  <div>
                  </div>
                  <div className="container mt-2 p-2">
                    <form>
                      <div className="row mb-5 mt-2">
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label htmlFor="company_logo" className="form-label">Company Logo <IsRequired />:</label>
                            <a href={`${this.state.company_logo_url}`}
                              className={`${!this.state.company_logo_url ? ('d-none') : ''} link-info link-offset-2 link-underline-opacity-100-hover`}
                              style={{ float: 'right' }}
                              target="_blank" rel="noopener noreferrer">
                              View Uploaded Logo
                              <i className="ri-arrow-right-line label-icon align-middle fs-16" />
                            </a>
                            <input
                              type="file"
                              id="company_logo"
                              name="company_logo"
                              accept=".jpg, .png, .jpeg"
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.company_logo ? 'is-invalid' : ''}`}
                            />
                            {errors.company_logo && <div className="invalid-feedback">{errors.company_logo}</div>}
                            {/* </div> */}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="company_code" className="form-label">Company Code <IsRequired />:</label>
                            <input
                              type="text"
                              id="company_code"
                              name="company_code"
                              value={this.state.company_code}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.company_code ? 'is-invalid' : ''}`}
                              placeholder="Enter Company Code"
                            />
                            {errors.company_code && <div className="invalid-feedback">{errors.company_code}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="company_name" className="form-label">Company Name <IsRequired /> :</label>
                            <input
                              type="text"
                              id="company_name"
                              name="company_name"
                              value={this.state.company_name}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.company_name ? 'is-invalid' : ''}`}
                              placeholder="Enter Company Name"
                            />
                            {errors.company_name && <div className="invalid-feedback">{errors.company_name}</div>}
                          </div>
                        </div>
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label htmlFor="email" className="form-label">Email Address <IsRequired /> :</label>
                            <input
                              type="email"
                              id="email"
                              name="email"
                              value={this.state.email}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.email ? 'is-invalid' : ''}`}
                              placeholder="Enter Email Address"
                            />
                            {errors.email && <div className="invalid-feedback">{errors.email}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="mobile_no" className="form-label">Mobile No. <IsRequired /> :</label>
                            <input
                              type="number"
                              id="mobile_no"
                              name="mobile_no"
                              value={this.state.mobile_no}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.mobile_no ? 'is-invalid' : ''}`}
                              placeholder="Enter Mobile No."
                            />
                            {errors.mobile_no && <div className="invalid-feedback">{errors.mobile_no}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="contact_person" className="form-label">Contact Person <IsRequired /> :</label>
                            <input
                              type="text"
                              id="contact_person"
                              name="contact_person"
                              value={this.state.contact_person}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.contact_person ? 'is-invalid' : ''}`}
                              placeholder="Enter Contact Person"
                            />
                            {errors.contact_person && <div className="invalid-feedback">{errors.contact_person}</div>}
                          </div>
                        </div>
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label htmlFor="register_office_address" className="form-label">Register Office Address <IsRequired /> :</label>
                            <textarea
                              id="register_office_address"
                              name="register_office_address"
                              value={this.state.register_office_address}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.register_office_address ? 'is-invalid' : ''}`}
                              placeholder="Enter Register Office Address"
                            />
                            {errors.register_office_address && <div className="invalid-feedback">{errors.register_office_address}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="address" className="form-label">Company Address <IsRequired /> :</label>
                            <textarea
                              id="address"
                              name="address"
                              value={this.state.address}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.address ? 'is-invalid' : ''}`}
                              placeholder="Enter Address"
                            />
                            {errors.address && <div className="invalid-feedback">{errors.address}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="register_office_location" className="form-label">Register Office Location:</label>
                            <textarea
                              id="register_office_location"
                              name="register_office_location"
                              value={this.state.register_office_location}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.register_office_location ? 'is-invalid' : ''}`}
                              placeholder="Enter Register Office Location"
                            />
                            {/* {errors.register_office_location && <div className="invalid-feedback">{errors.register_office_location}</div>} */}
                          </div>
                        </div>
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label htmlFor="registration_number" className="form-label">Registration Number:</label>
                            <input
                              type="text"
                              id="registration_number"
                              name="registration_number"
                              value={this.state.registration_number}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.registration_number ? 'is-invalid' : ''}`}
                              placeholder="Enter Registration Number"
                            />
                            {/* {errors.registration_number && <div className="invalid-feedback">{errors.registration_number}</div>} */}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="nature_of_business" className="form-label">Nature Of Business <IsRequired /> :</label>
                            <input
                              type="text"
                              id="nature_of_business"
                              name="nature_of_business"
                              value={this.state.nature_of_business}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.nature_of_business ? 'is-invalid' : ''}`}
                              placeholder="Enter Nature Of Business"
                            />
                            {errors.nature_of_business && <div className="invalid-feedback">{errors.nature_of_business}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="type_of_company" className="form-label">Type of Company <IsRequired /> :</label>
                            <input
                              type="text"
                              id="type_of_company"
                              name="type_of_company"
                              value={this.state.type_of_company}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.type_of_company ? 'is-invalid' : ''}`}
                              placeholder="Enter Type of Company"
                            />
                            {errors.type_of_company && <div className="invalid-feedback">{errors.type_of_company}</div>}
                          </div>
                        </div>
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label htmlFor="date_of_establishment" className="form-label">Date Of Establishment <IsRequired /> :</label>
                            <input
                              type="date"
                              id="date_of_establishment"
                              name="date_of_establishment"
                              value={this.state.date_of_establishment}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.date_of_establishment ? 'is-invalid' : ''}`}
                            />
                            {errors.date_of_establishment && <div className="invalid-feedback">{errors.date_of_establishment}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="contract_start_date" className="form-label">Contract Start Date <IsRequired /> :</label>
                            <input
                              type="date"
                              id="contract_start_date"
                              name="contract_start_date"
                              value={this.state.contract_start_date}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.contract_start_date ? 'is-invalid' : ''}`}
                            />
                            {errors.contract_start_date && <div className="invalid-feedback">{errors.contract_start_date}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="contract_end_date" className="form-label">Contract End Date:</label>
                            <input
                              type="date"
                              id="contract_end_date"
                              name="contract_end_date"
                              value={this.state.contract_end_date}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.contract_end_date ? 'is-invalid' : ''}`}
                            />
                            {/* {errors.contract_end_date && <div className="invalid-feedback">{errors.contract_end_date}</div>} */}
                          </div>
                        </div>
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label htmlFor="total_employees" className="form-label">Total Employees <IsRequired /> :</label>
                            <input
                              type="number"
                              id="total_employees"
                              name="total_employees"
                              value={this.state.total_employees}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.total_employees ? 'is-invalid' : ''}`}
                              placeholder="Enter Total Employees"
                            />
                            {errors.total_employees && <div className="invalid-feedback">{errors.total_employees}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="pincode" className="form-label">Pin-code <IsRequired /> :</label>
                            <input
                              type="text"
                              id="pincode"
                              name="pincode"
                              value={this.state.pincode}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.pincode ? 'is-invalid' : ''}`}
                              placeholder="Enter Pincode"
                            />
                            {errors.pincode && <div className="invalid-feedback">{errors.pincode}</div>}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="country" className="form-label">Country <IsRequired /> :</label>
                            <input
                              type="text"
                              id="country"
                              name="country"
                              value={this.state.country}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.country ? 'is-invalid' : ''}`}
                              placeholder="Enter Country"
                            />
                            {errors.country && <div className="invalid-feedback">{errors.country}</div>}
                          </div>
                        </div>
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label htmlFor="state" className="form-label">State:</label>
                            <input
                              type="text"
                              id="state"
                              name="state"
                              value={this.state.state}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.state ? 'is-invalid' : ''}`}
                              placeholder="Enter State"
                            />
                            {/* {errors.state && <div className="invalid-feedback">{errors.state}</div>} */}
                          </div>
                          <div className="col-md-4">
                            <label htmlFor="twitter_handler" className="form-label">Twitter Handler:</label>
                            <input
                              type="text"
                              id="twitter_handler"
                              name="twitter_handler"
                              value={this.state.twitter_handler}
                              onChange={this.handleInputChange}
                              className={`form-control ${errors.twitter_handler ? 'is-invalid' : ''}`}
                              placeholder="Enter Twitter Handler"
                            />
                            {/* {errors.twitter_handler && <div className="invalid-feedback">{errors.twitter_handler}</div>} */}
                          </div>
                          <div className="col-md-2" style={{ marginTop: "35px" }}>
                            <label className="form-check-label" style={{ marginRight: "10px" }} for="pt_applicable">PT Applicable : </label>

                            <input
                              type="checkbox"
                              id="pt_applicable"
                              name="pt_applicable"
                              checked={this.state.pt_applicable}
                              onChange={this.handleCheckboxChange}
                              className="form-check-input"
                            />
                          </div>
                          <div className="col-md-2" style={{ marginTop: "35px" }}>
                            <label className="form-check-label" for="lwf_applicable" style={{ marginRight: "10px" }}>LWF Applicable : </label>

                            <input
                              type="checkbox"
                              id="lwf_applicable"
                              name="lwf_applicable"
                              checked={this.state.lwf_applicable}
                              onChange={this.handleCheckboxChange}
                              className="form-check-input"
                            />
                          </div>
                        </div>
                        <div className="row mb-3">
                          <div className="col-md-4">
                            <label className="form-label">Service Offer:</label>
                            <div>
                              <label htmlFor="service_offer_abstart" className="form-check-label" style={{ marginRight: "5px" }}>ABStart </label>
                              <input
                                type="radio"
                                id="service_offer_abstart"
                                name="service_offer"
                                value="ABStart"
                                checked={this.state.service_offer === "ABStart"}
                                onChange={this.handleInputChange}
                                className="form-check-input"
                              />

                              <label htmlFor="service_offer_staffing" style={{ marginLeft: "20px", marginRight: "5px" }} className="form-check-label">Staffing </label>
                              <input
                                type="radio"
                                id="service_offer_staffing"
                                name="service_offer"
                                value="Staffing"
                                checked={this.state.service_offer === "Staffing"}
                                onChange={this.handleInputChange}
                                className="form-check-input"
                              />
                              <label htmlFor="service_offer_saas" style={{ marginLeft: "20px", marginRight: "5px" }} className="form-check-label">SAAS </label>
                              <input
                                type="radio"
                                id="service_offer_saas"
                                name="service_offer"
                                value="SAAS"
                                checked={this.state.service_offer === "SAAS"}
                                onChange={this.handleInputChange}
                                className="form-check-input"
                              />
                            </div>
                            {errors.service_offer && <div className="invalid-feedback d-block">{errors.service_offer}</div>}
                          </div>
                        </div>
                      </div>
                    </form>
                    {!this.props.params.company_id ? (
                      <div className="d-flex justify-content-end">
                        <button type="button" disabled={this.state.postLoading} onClick={this.handleSubmit} className="btn btn-success btn-label waves-effect right waves-light">
                          <i className="bx bx-add-to-queue label-icon align-middle fs-16 ms-2" /> Create
                        </button>
                      </div>
                    ) : <div className="d-flex justify-content-end">
                      <button type="button" disabled={this.state.postLoading} onClick={this.handleSubmit} className="btn btn-success btn-label waves-effect right waves-light">
                        <i className=" ri-edit-box-line label-icon align-middle fs-16 ms-2" /> Updated
                      </button>
                      <NavLink to={"/CompanyList"} ref={this.closeRef} type="button" disabled={this.state.postLoading} onClick={this.resetForm} className="btn btn-light btn-label waves-effect right waves-light" style={{ marginLeft: "10px" }}>
                        <i className="ri-close-fill label-icon align-middle fs-16 ms-2" /> Cancel
                      </NavLink>
                    </div>
                    }
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div >
      </div >

    );
  }
}

export default withRouter(CreateCompany);
