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

class CompanyList extends Component {
  static contextType = ConfigContext;
  constructor(props) {
    super(props);
    this.state = {
      company_id: 0,
      rows: [],
      next: false,
      prev: false,
      page: 1,
      limit: 10,
      total_records: 0,
      total_pages: 0,
      loadingList: false,
      keyword: "",
      from_date: "",
      to_date: "",
      selectOption: "",
    };
  }
  componentDidMount() {
    this.setState({ loadingList: true }, (prevState) => {
      this.GetList();
    });
  }

  GetList = () => {
    const { apiURL, apiHeaderJson } = this.context;
    const headers = apiHeaderJson;

    axios
      .get(`${apiURL}Companies/GetCompanies`, {
        params: {
          limit: this.state.limit,
          page: this.state.page,
          keyword: this.state.keyword,
          from_date: this.state.from_date,
          to_date: this.state.to_date,
        },
        headers,
      })
      .then((response) => {
        console.log(`response`, response);
        var data = response.data;
        if (response.data.success === true) {
          this.setState({
            rows: data.data,
            next: data.next,
            prev: data.prev,
            page: data.page,
            total_records: data.total_records,
            total_pages: data.total_pages,
            loadingList: false,
          });
        } else {
          Swal.fire('Error..!!', `${data.message}`, 'error');
          this.setState({ loadingList: false });
        }
      });
  };

  handleDelete = (id) => {
    const { apiURL, apiHeaderJson } = this.context;
    const headers = apiHeaderJson;
    Swal.fire({
      title: "Are you sure?",
      text: "You won't be able to revert this!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, delete it!",
    }).then((result) => {
      if (result.isConfirmed) {
        this.setState({ status: true });
        const formData = {
          employee_id: id,
        };
        axios
          .post(`${apiURL}Employees/DeleteEmployee`, formData, { headers })
          .then((response) => {
            Swal.fire({
              title: `<strong>${response.data.success === true ? "Success" : "Failed"
                }</strong>`,
              text: response.data.message,
              icon: response.data.success === true ? "success" : "error",
            });
            this.setState({ status: false });
            if (response.data.success === true) {
              this.setState({ loadingList: true }, (prevState) => {
                this.GetList();
              });
            }
          })
          .catch((error) => {
            Swal.fire({
              title: <strong>Error</strong>,
              html: error,
              icon: "error",
            });
          });
      }
    });
  };

  handleInputSearch = (e) => {
    this.GetList();
  }

  handleInputChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };
  handleSelectChange = (selectedOption) => {
    this.setState({ selectOption: selectedOption });
  };
  handleClearAll = () => {
    this.setState({
      company_id: 0,
      rows: [],
      next: false,
      prev: false,
      page: 1,
      limit: 10,
      total_records: 0,
      total_pages: 0,
      loadingList: false,
      postLoading: false,
      keyword: "",
      from_date: "",
      to_date: "",
      selectOption: "",
    }
      , () => {
        this.GetList();
      });
  };


  handlePrev = (ev) => {
    if (this.state.prev === true) {
      this.setState(
        (prevState) => {
          return { page: prevState.page - 1 };
        },
        () => {
          this.GetList(); // This will log the updated state value
        }
      );
    }
  };
  handleNext = () => {
    if (this.state.next === true) {
      this.setState(
        (prevState) => {
          return { page: prevState.page + 1 };
        },
        () => {
          this.GetList(); // This will log the updated state value
        }
      );
    }
  };
  handleChange = (e) => {
    this.setState(
      (prevState) => {
        return { page: parseInt(e.target.value, 10) };
      },
      () => {
        this.GetList(); // This will log the updated state value
      }
    );
  };
  render() {
    const { loadingList } = this.state;
    return (
      <div className="main-content">
        <div className="page-content">
          {loadingList === false ? (
            <div className="container-fluid">
              <br />
              <PageTitle title={`Employee List`} primary={`Home`} />
              <div className="row">
                <div className="col-md-12">
                  <div className="card">
                    <div className="card-header">
                      <div className="row">
                        <div className='col-md-3'>
                          <label htmlFor="keyword">Company Name</label>
                          <div className="input-group">
                            <input type="search" className="form-control" onChange={this.handleInputChange} name="keyword" id="keyword" value={this.state.keyword} aria-label="Recipient's username" aria-describedby="button-addon2" placeholder="Search By Company Name" />
                            <button className="btn btn-success" onClick={this.handleInputSearch} disabled={!this.state.keyword} type="button" id="button-addon2"><i className="ri-search-line"></i></button>
                          </div>
                        </div>
                        <div className='col-md-3'>
                          <TextBox type="Date" id="from_date" name="from_date" label="From date" value={this.state.from_date} change={this.handleInputChange} />
                        </div>
                        <div className='col-md-3'>
                          <TextBox type="Date" id="to_date" name="to_date" label="To date" value={this.state.to_date} change={this.handleInputChange} />
                        </div>
                        <div className='col-md-3'>
                          <div className='row'>
                            <div className='col-md-6'>
                              <div>
                                <label>Filter</label>
                              </div>
                              <button
                                type="button"
                                className={`btn btn-info btn-label right ms-auto  ${(!this.state.keyword && !this.state.from_date && !this.state.to_date && !this.state.selectOption) ? 'disabled' : ''}`}
                                onClick={this.handleInputSearch}
                                disabled={!this.state.keyword && !this.state.from_date && !this.state.to_date && !this.state.selectOption}>
                                <i className="ri-filter-3-fill label-icon align-middle fs-16 ms-2"></i> Filter</button>
                            </div>
                            <div className='col-md-6'>
                              <div>
                                <label>Show All </label>
                              </div>
                              <button
                                type="button"
                                className={`btn btn-secondary btn-label right ms-auto  ${(!this.state.keyword && !this.state.from_date && !this.state.to_date && !this.state.selectOption) ? 'disabled' : ''}`}
                                onClick={this.handleClearAll}
                                disabled={!this.state.keyword && !this.state.from_date && !this.state.to_date && !this.state.selectOption}>
                                <i className=" ri-database-2-line label-icon align-middle fs-16 ms-2"></i> Show All
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="table-responsive card-body">
                      <table className={`table table-bordered table-stripped`}>
                        <thead className="table-light">
                          <tr>
                            <th>Company Logo</th>
                            <th>Company Code</th>
                            <th>Company Name</th>
                            <th>Company Email</th>
                            <th>Company Mobile Number</th>
                            <th>Company Address</th>

                            <th className="text-center" width={100}>Action</th>
                          </tr>
                        </thead>
                        {this.state.rows.length !== 0 ? (
                          <tbody>
                            {
                              this.state.rows.map((row) => (
                                <tr key={row.company_id}>
                                  <td>
                                    {row.company_logo_url === null ? (
                                      <small className="text-bolder">Company Logo is Not Uploaded</small>
                                    ) :
                                      <div className="d-flex justify-content-center align-items-center">
                                        <img src={`${row.company_logo_url}`} alt="Company Logo" className="bg-light p-1" style={{ width: "100px", borderRadius: "100px", aspectRatio: "3/2", objectFit: "contain" }} />
                                      </div>
                                    }
                                  </td>
                                  <td>{row.company_code}</td>
                                  <td>{row.company_name}</td>
                                  <td>{row.email_address}</td>
                                  <td>{row.mobile_number}</td>
                                  <td>
                                    <div style={{ width: '200px', textOverflow: "ellipsis", whiteSpace: "nowrap", overflow: "hidden" }} title={`${row.company_address}`}>
                                      {row.company_address}
                                    </div>
                                  </td>
                                  <td className="d-flex justify-content-around">
                                    <NavLink to={`/CreateCompany/${row.company_id}`}>
                                      <button
                                        type="button"
                                        className="btn-icon btn btn-sm btn-outline-primary"
                                      >
                                        <i className="ri-edit-box-line"></i>
                                      </button>
                                    </NavLink>
                                    <button
                                      onClick={() => this.handleDelete(row.company_id)}
                                      className="btn-icon btn btn-sm btn-outline-danger"
                                    >
                                      <i className="ri-delete-bin-line"></i>
                                    </button>
                                  </td>
                                </tr>
                              ))}
                          </tbody>
                        ) : (
                          <tbody>
                            <tr>
                              <td colSpan="7">
                                <NoRecords />
                              </td>
                            </tr>
                          </tbody>
                        )}
                        <tfoot className="table-light">
                          <tr>
                            <th colSpan={7}>
                              <div className="d-flex justify-content-between">
                                <button
                                  disabled={this.state.prev === false && this.state.loadingList === false ? true : false}
                                  type="button"
                                  onClick={() => this.handlePrev()}
                                  className={`btn btn-warning btn-label waves-effect waves-light`}
                                >
                                  <i className="ri-arrow-left-line label-icon align-middle fs-16 me-2" />
                                  Previous
                                </button>
                                <div
                                  className="col-md-4"
                                  style={{ display: "flex", alignItems: "center" }}
                                >
                                  {
                                    <small>
                                      Total Records: {this.state.total_records} |
                                      Total Pages: {this.state.total_pages} |
                                      Current Page: {this.state.page}
                                    </small>
                                  }
                                </div>
                                <div className="col-md-2">
                                  <select
                                    className="form-select"
                                    onChange={(e) => this.handleChange(e)}
                                  >
                                    {Array.from(
                                      { length: this.state.total_pages },
                                      (_, i) => (
                                        <option
                                          selected={this.state.page === i + 1}
                                          key={i}
                                          value={i + 1}
                                        >
                                          Page {i + 1}
                                        </option>
                                      )
                                    )}
                                  </select>
                                </div>
                                <button
                                  disabled={
                                    this.state.next === false &&
                                      this.state.loadingList === false
                                      ? true
                                      : false
                                  }
                                  type="button"
                                  onClick={() => this.handleNext()}
                                  className={`btn btn-primary btn-label waves-effect right waves-light`}
                                >
                                  <i className="ri-arrow-right-line label-icon align-middle fs-16 ms-2" />
                                  Next
                                </button>
                              </div>
                            </th>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ) :
            <ContentLoader />
          }
        </div>
      </div >
    );
  }
}
export default withRouter(CompanyList);