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";

function JobLinesContainer({ jobId }) {
  const { loading, error, data, refetch } = useQuery(GET_JOB_LINES_BY_PK, {
    variables: { id: jobId },
  });

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

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

  const 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;

  return (
    <JobLinesComponent
      loading={loading}
      refetch={refetch}
      jobLines={jobLines}
      setSearchText={setSearchText}
      selectedLines={selectedLines}
      setSelectedLines={setSelectedLines}
      jobId={jobId}
    />
  );
}

export default JobLinesContainer;
