import { useQuery } from "@apollo/react-hooks";
import React, { useState } from "react";

import { GET_JOB_LINES_BY_PK } from "../../graphql/jobs-lines.queries";
import AlertComponent from "../alert/alert.component";
import JobLinesComponent from "./job-lines.component";

import { connect } from "react-redux";
import { setModalContext } from "../../redux/modals/modals.actions";
const mapDispatchToProps = dispatch => ({
  setJobLineEditContext: context =>
    dispatch(setModalContext({ context: context, modal: "jobLineEdit" }))
});
export default connect(
  null,
  mapDispatchToProps
)(function JobLinesContainer({ jobId, setJobLineEditContext }) {
  const { loading, error, data, refetch } = useQuery(GET_JOB_LINES_BY_PK, {
    variables: { id: jobId },
    fetchPolicy: "network-only"
  });

  const [searchText, setSearchText] = useState("");
  const [selectedLines, setSelectedLines] = useState([]);
  const partsOrderModalVisible = useState(false);

  if (error) return <AlertComponent message={error.message} type="error" />;

  return (
    <JobLinesComponent
      loading={loading}
      refetch={refetch}
      jobLines={
        data && data.joblines
          ? searchText
            ? data.joblines.filter(
                jl =>
                  (jl.unq_seq || "")
                    .toString()
                    .toLowerCase()
                    .includes(searchText.toLowerCase()) ||
                  (jl.line_desc || "")
                    .toLowerCase()
                    .includes(searchText.toLowerCase()) ||
                  (jl.part_type || "")
                    .toLowerCase()
                    .includes(searchText.toLowerCase()) ||
                  (jl.oem_partno || "")
                    .toLowerCase()
                    .includes(searchText.toLowerCase()) ||
                  (jl.op_code_desc || "")
                    .toLowerCase()
                    .includes(searchText.toLowerCase()) ||
                  (jl.db_price || "")
                    .toString()
                    .includes(searchText.toLowerCase()) ||
                  (jl.act_price || "")
                    .toString()
                    .includes(searchText.toLowerCase())
              )
            : data.joblines
          : null
      }
      setSearchText={setSearchText}
      selectedLines={selectedLines}
      setSelectedLines={setSelectedLines}
      partsOrderModalVisible={partsOrderModalVisible}
      jobId={jobId}
      setJobLineEditContext={setJobLineEditContext}
    />
  );
});
