import { useQuery } from "@apollo/react-hooks";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import AlertComponent from "../../components/alert/alert.component";
import JobDetailCards from "../../components/job-detail-cards/job-detail-cards.component";
import JobsList from "../../components/jobs-list/jobs-list.component";
import { QUERY_ALL_ACTIVE_JOBS } from "../../graphql/jobs.queries";

import { selectBodyshop } from "../../redux/user/user.selectors";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

export default connect(
  mapStateToProps,
  null
)(function JobsPage({ match, location, bodyshop }) {
  const { loading, error, data, refetch } = useQuery(QUERY_ALL_ACTIVE_JOBS, {
    fetchPolicy: "network-only",
    variables: {
      statuses: bodyshop.md_ro_statuses.open_statuses || ["Open"]
    }
  });
  const { t } = useTranslation();

  useEffect(() => {
    document.title = t("titles.jobs");
  }, [t]);

  const { hash } = location;
  const [selectedJob, setSelectedJob] = useState(hash ? hash.substr(1) : null);
  const searchTextState = useState("");
  const searchText = searchTextState[0];
  if (error) return <AlertComponent message={error.message} type='error' />;
  //TODO Implement pagination for this.

  console.log(typeof searchText);
  return (
    <div>
      <JobsList
        searchTextState={searchTextState}
        refetch={refetch}
        loading={loading}
        selectedJob={selectedJob}
        setSelectedJob={setSelectedJob}
        jobs={
          data
            ? searchTextState[0] === ""
              ? data.jobs
              : data.jobs.filter(
                  j =>
                    (j.ro_number || "")
                      .toString()
                      .toLowerCase()
                      .includes(searchText.toLowerCase()) ||
                    (j.ownr_fn || "")
                      .toLowerCase()
                      .includes(searchText.toLowerCase()) ||
                    (j.ownr_ln || "")
                      .toLowerCase()
                      .includes(searchText.toLowerCase()) ||
                    (j.clm_no || "")
                      .toLowerCase()
                      .includes(searchText.toLowerCase()) ||
                    (j.vehicle.plate_no || "")
                      .toLowerCase()
                      .includes(searchText.toLowerCase()) ||
                    (j.vehicle.v_model_desc || "")
                      .toLowerCase()
                      .includes(searchText.toLowerCase()) ||
                    (j.vehicle.v_make_desc || "")
                      .toLowerCase()
                      .includes(searchText.toLowerCase())
                )
            : null
        }
      />
      <JobDetailCards selectedJob={selectedJob} />
    </div>
  );
});
