import {
  DeleteFilled,
  EditFilled,
  FilterFilled,
  HomeOutlined,
  MinusCircleTwoTone,
  PlusCircleTwoTone,
  SyncOutlined,
  WarningFilled
} from "@ant-design/icons";
import { PageHeader } from "@ant-design/pro-layout";
import { useMutation } from "@apollo/client/react";
import { gql } from "@apollo/client";
import { Button, Dropdown, Input, Modal, Select, Space, Table, Tag, Typography } from "antd";
import axios from "axios";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { DELETE_JOB_LINE_BY_PK } from "../../graphql/jobs-lines.queries";
import { selectIsPartsEntry, selectJobReadOnly } from "../../redux/application/application.selectors";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { onlyUnique } from "../../utils/arrayHelper";
import { alphaSort } from "../../utils/sorters";
import JobLineLocationPopup from "../job-line-location-popup/job-line-location-popup.component";
import JobLineNotePopup from "../job-line-note-popup/job-line-note-popup.component";
import JobLineStatusPopup from "../job-line-status-popup/job-line-status-popup.component";
import JobLinesBillRefernece from "../job-lines-bill-reference/job-lines-bill-reference.component";
// import AllocationsAssignmentContainer from "../allocations-assignment/allocations-assignment.container";
// import AllocationsBulkAssignmentContainer from "../allocations-bulk-assignment/allocations-bulk-assignment.container";
// import AllocationsEmployeeLabelContainer from "../allocations-employee-label/allocations-employee-label.container";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import _ from "lodash";
import { FaTasks } from "react-icons/fa";
import { selectAuthLevel, selectBodyshop } from "../../redux/user/user.selectors";
import dayjs from "../../utils/day";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";
import JobCreateIOU from "../job-create-iou/job-create-iou.component";
import JobLineBulkAssignComponent from "../job-line-bulk-assign/job-line-bulk-assign.component";
import JobLineDispatchButton from "../job-line-dispatch-button/job-line-dispatch-button.component";
import JoblineTeamAssignment from "../job-line-team-assignment/job-line-team-assignmnent.component";
import JobSendPartPriceChangeComponent from "../job-send-parts-price-change/job-send-parts-price-change.component";
import PartsOrderDrawer from "../parts-order-list-table/parts-order-list-table-drawer.component";
import PartsOrderModalContainer from "../parts-order-modal/parts-order-modal.container";
import { buildInHouseBillLines } from "./job-lines.in-house-bill-lines.utils";
import JobLinesExpander from "./job-lines-expander.component";
import JobLinesPartPriceChange from "./job-lines-part-price-change.component";
import JobLinesExpanderSimple from "./jobs-lines-expander-simple.component";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { HasRbacAccess } from "../rbac-wrapper/rbac-wrapper.component.jsx";

const UPDATE_JOB_LINES_LOCATION_BULK = gql`
  mutation UPDATE_JOB_LINES_LOCATION_BULK($ids: [uuid!]!, $location: String!) {
    update_joblines(where: { id: { _in: $ids } }, _set: { location: $location }) {
      affected_rows
      returning {
        id
        location
      }
    }
  }
`;

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly,
  technician: selectTechnician,
  isPartsEntry: selectIsPartsEntry,
  authLevel: selectAuthLevel
});

const mapDispatchToProps = (dispatch) => ({
  setJobLineEditContext: (context) => dispatch(setModalContext({ context: context, modal: "jobLineEdit" })),
  setPartsOrderContext: (context) => dispatch(setModalContext({ context: context, modal: "partsOrder" })),
  setPartsReceiveContext: (context) => dispatch(setModalContext({ context: context, modal: "partsReceive" })),
  setBillEnterContext: (context) => dispatch(setModalContext({ context: context, modal: "billEnter" })),
  setTaskUpsertContext: (context) => dispatch(setModalContext({ context, modal: "taskUpsert" }))
});

export function JobLinesComponent({
  bodyshop,
  jobRO,
  technician,
  setPartsOrderContext,
  setPartsReceiveContext,
  loading,
  refetch,
  jobLines,
  setSearchText,
  job,
  setJobLineEditContext,
  form,
  setBillEnterContext,
  setTaskUpsertContext,
  billsQuery,
  handlePartsOrderOnRowClick,
  isPartsEntry,
  authLevel
}) {
  const [deleteJobLine] = useMutation(DELETE_JOB_LINE_BY_PK);
  const [bulkUpdateLocations] = useMutation(UPDATE_JOB_LINES_LOCATION_BULK);
  const notification = useNotification();

  const {
    treatments: { Enhanced_Payroll }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });

  const [selectedLines, setSelectedLines] = useState([]);
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: {
      ...(isPartsEntry
        ? {
            part_type: ["PAN", "PAC", "PAR", "PAL", "PAA", "PAM", "PAP", "PAS", "PASL", "PAG"] //"PAO" Removed by request
          }
        : {})
    }
  });

  // Bulk location modal state
  const [bulkLocationOpen, setBulkLocationOpen] = useState(false);
  const [bulkLocation, setBulkLocation] = useState(null);
  const [bulkLocationSaving, setBulkLocationSaving] = useState(false);

  const { t } = useTranslation();
  const jobIsPrivate = bodyshop.md_ins_cos.find((c) => c.name === job.ins_co_nm)?.private;

  const selectedLineIds = useMemo(() => selectedLines.map((l) => l?.id).filter(Boolean), [selectedLines]);

  const commonSelectedLocation = useMemo(() => {
    const locs = selectedLines
      .map((l) => (typeof l?.location === "string" ? l.location : ""))
      .map((x) => x.trim())
      .filter(Boolean);

    if (locs.length === 0) return null;

    const uniq = _.uniq(locs);
    return uniq.length === 1 ? uniq[0] : null;
  }, [selectedLines]);

  const openBulkLocationModal = () => {
    setBulkLocation(commonSelectedLocation);
    setBulkLocationOpen(true);
    logImEXEvent("joblines_bulk_location_open", { count: selectedLineIds.length });
  };

  const closeBulkLocationModal = () => {
    setBulkLocationOpen(false);
    setBulkLocation(null);
  };

  const saveBulkLocation = async () => {
    if (selectedLineIds.length === 0) return;

    setBulkLocationSaving(true);

    try {
      const locationToSave = (bulkLocation ?? "").toString();

      const result = await bulkUpdateLocations({
        variables: {
          ids: selectedLineIds,
          location: locationToSave
        }
      });

      if (!result?.errors) {
        // Keep UI selection consistent without waiting for refetch
        setSelectedLines((prev) =>
          prev.map((l) => (l && selectedLineIds.includes(l.id) ? { ...l, location: locationToSave } : l))
        );

        notification.success({ title: t("joblines.successes.saved") });

        logImEXEvent("joblines_bulk_location_saved", {
          count: selectedLineIds.length,
          location: locationToSave
        });

        closeBulkLocationModal();
        if (refetch) refetch();
      } else {
        notification.error({
          title: t("joblines.errors.saving", { error: JSON.stringify(result.errors) })
        });
      }
    } catch (error) {
      notification.error({
        title: t("joblines.errors.saving", { error: error?.message || String(error) })
      });
    } finally {
      setBulkLocationSaving(false);
    }
  };

  const columns = [
    {
      title: "#",
      dataIndex: "line_no",
      key: "line_no",
      sorter: (a, b) => a.line_no - b.line_no,
      fixed: "left",
      sortOrder: state.sortedInfo.columnKey === "line_no" && state.sortedInfo.order
    },
    {
      title: t("joblines.fields.line_desc"),
      dataIndex: "line_desc",
      fixed: "left",
      key: "line_desc",
      sorter: (a, b) => alphaSort(a.line_desc, b.line_desc),
      onCell: (record) => ({
        className: record.manual_line && "job-line-manual",
        style: {
          ...(record.critical ? { boxShadow: " -.5em 0 0 #FFC107" } : {})
        }
      }),
      sortOrder: state.sortedInfo.columnKey === "line_desc" && state.sortedInfo.order
    },
    {
      title: t("joblines.fields.oem_partno"),
      dataIndex: "oem_partno",
      key: "oem_partno",
      sorter: (a, b) => alphaSort(a.oem_partno, b.oem_partno),
      sortOrder: state.sortedInfo.columnKey === "oem_partno" && state.sortedInfo.order,
      ellipsis: true,
      onCell: (record) => ({
        className: record.manual_line && "job-line-manual",
        style: {
          ...(record.parts_dispatch_lines[0]?.accepted_at ? { boxShadow: " -.5em 0 0 #FFC107" } : {})
        }
      }),
      render: (text, record) => (
        <span className="ant-table-cell-content">
          {`${record.oem_partno || ""} ${record.alt_partno ? `(${record.alt_partno})` : ""}`.trim()}
        </span>
      )
    },
    {
      title: t("joblines.fields.op_code_desc"),
      dataIndex: "op_code_desc",
      key: "op_code_desc",
      sorter: (a, b) => alphaSort(a.op_code_desc, b.op_code_desc),
      sortOrder: state.sortedInfo.columnKey === "op_code_desc" && state.sortedInfo.order,
      ellipsis: true,
      render: (text, record) => `${record.op_code_desc || ""}${record.alt_partm ? ` ${record.alt_partm}` : ""}`
    },
    {
      title: t("joblines.fields.part_type"),
      dataIndex: "part_type",
      key: "part_type",
      filteredValue: state.filteredInfo.part_type || null,
      sorter: (a, b) => alphaSort(a.part_type, b.part_type),
      sortOrder: state.sortedInfo.columnKey === "part_type" && state.sortedInfo.order,
      filters: [
        {
          text: t("jobs.labels.partsfilter"),
          value: isPartsEntry
            ? ["PAN", "PAC", "PAR", "PAL", "PAA", "PAM", "PAP", "PAS", "PASL", "PAG", "PAO"]
            : ["PAN", "PAC", "PAR", "PAL", "PAA", "PAM", "PAP", "PAS", "PASL", "PAG"]
        },
        { text: t("joblines.fields.part_types.PAN"), value: ["PAN"] },
        { text: t("joblines.fields.part_types.PAP"), value: ["PAP"] },
        { text: t("joblines.fields.part_types.PAL"), value: ["PAL"] },
        { text: t("joblines.fields.part_types.PAA"), value: ["PAA"] },
        { text: t("joblines.fields.part_types.PAG"), value: ["PAG"] },
        { text: t("joblines.fields.part_types.PAS"), value: ["PAS"] },
        { text: t("joblines.fields.part_types.PASL"), value: ["PASL"] },
        { text: t("joblines.fields.part_types.PAC"), value: ["PAC"] },
        { text: t("joblines.fields.part_types.PAR"), value: ["PAR"] },
        { text: t("joblines.fields.part_types.PAM"), value: ["PAM"] },
        ...(isPartsEntry
          ? [
              {
                text: t("joblines.fields.part_types.PAO"),
                value: ["PAO"]
              }
            ]
          : [])
      ],
      onFilter: (value, record) => value.includes(record.part_type),
      render: (text, record) => (record.part_type ? t(`joblines.fields.part_types.${record.part_type}`) : null)
    },
    {
      title: t("joblines.fields.act_price"),
      dataIndex: "act_price",
      key: "act_price",
      sorter: (a, b) => a.act_price - b.act_price,
      sortOrder: state.sortedInfo.columnKey === "act_price" && state.sortedInfo.order,
      ellipsis: true,
      render: (text, record) => <JobLinesPartPriceChange line={record} job={job} refetch={refetch} />
    },
    {
      title: t("joblines.fields.part_qty"),
      dataIndex: "part_qty",
      key: "part_qty",
      sorter: (a, b) => a.part_qty - b.part_qty,
      sortOrder: state.sortedInfo.columnKey === "part_qty" && state.sortedInfo.order
    },
    ...(!isPartsEntry
      ? [
          {
            title: t("joblines.fields.mod_lbr_ty"),
            dataIndex: "mod_lbr_ty",
            key: "mod_lbr_ty",
            sorter: (a, b) => alphaSort(a.mod_lbr_ty, b.mod_lbr_ty),
            sortOrder: state.sortedInfo.columnKey === "mod_lbr_ty" && state.sortedInfo.order,
            render: (text, record) => (record.mod_lbr_ty ? t(`joblines.fields.lbr_types.${record.mod_lbr_ty}`) : null)
          },
          {
            title: t("joblines.fields.mod_lb_hrs"),
            dataIndex: "mod_lb_hrs",
            key: "mod_lb_hrs",
            sorter: (a, b) => a.mod_lb_hrs - b.mod_lb_hrs,
            sortOrder: state.sortedInfo.columnKey === "mod_lb_hrs" && state.sortedInfo.order
          },
          {
            title: t("joblines.fields.line_ind"),
            dataIndex: "line_ind",
            key: "line_ind",
            sorter: (a, b) => alphaSort(a.line_ind, b.line_ind),
            sortOrder: state.sortedInfo.columnKey === "line_ind" && state.sortedInfo.order,
            responsive: ["md"]
          },
          ...(Enhanced_Payroll.treatment === "on"
            ? [
                {
                  title: t("joblines.fields.assigned_team"),
                  dataIndex: "assigned_team",
                  key: "assigned_team",
                  render: (text, record) => <JoblineTeamAssignment disabled={jobRO} jobline={record} jobId={job.id} />
                }
              ]
            : [])
        ]
      : []),

    {
      title: t("joblines.fields.notes"),
      dataIndex: "notes",
      key: "notes",
      render: (text, record) => <JobLineNotePopup disabled={jobRO} jobline={record} />
    },
    {
      title: t("joblines.fields.location"),
      dataIndex: "location",
      key: "location",
      render: (text, record) => <JobLineLocationPopup jobline={record} disabled={jobRO} />
    },
    ...(!isPartsEntry && HasFeatureAccess({ featureName: "bills", bodyshop })
      ? [
          {
            title: t("joblines.labels.billref"),
            dataIndex: "billref",
            key: "billref",
            render: (text, record) => <JobLinesBillRefernece jobline={record} />,
            responsive: ["md"]
          }
        ]
      : []),
    {
      title: t("joblines.fields.status"),
      dataIndex: "status",
      key: "status",
      sorter: (a, b) => alphaSort(a.status, b.status),
      sortOrder: state.sortedInfo.columnKey === "status" && state.sortedInfo.order,
      filteredValue: state.filteredInfo.status || null,
      filters:
        (jobLines &&
          jobLines
            .map((l) => l.status)
            .filter(onlyUnique)
            .map((s) => ({ text: s || t("dashboard.errors.status"), value: [s] }))) ||
        [],
      onFilter: (value, record) => value.includes(record.status),
      render: (text, record) => <JobLineStatusPopup jobline={record} disabled={jobRO} />
    },
    ...(!isPartsEntry
      ? [
          {
            title: t("general.labels.actions"),
            dataIndex: "actions",
            key: "actions",
            render: (text, record) => (
              <Space>
                {(record.manual_line || jobIsPrivate) &&
                  !technician &&
                  HasRbacAccess({ bodyshop, authLevel, action: "jobs:manual-line" }) && (
                    <Button
                      disabled={jobRO}
                      onClick={() => {
                        setJobLineEditContext({
                          actions: { refetch: refetch, submit: form && form.submit },
                          context: { ...record, jobid: job.id }
                        });
                      }}
                      icon={<EditFilled />}
                    />
                  )}
                <Button
                  title={t("tasks.buttons.create")}
                  onClick={() => {
                    setTaskUpsertContext({
                      context: {
                        jobid: job.id,
                        joblineid: record.id
                      }
                    });
                  }}
                  icon={<FaTasks />}
                />
                {(record.manual_line || jobIsPrivate) &&
                  !technician &&
                  HasRbacAccess({ bodyshop, authLevel, action: "jobs:manual-line" }) && (
                    <Button
                      disabled={jobRO}
                      onClick={async () => {
                        await deleteJobLine({
                          variables: { joblineId: record.id },
                          update(cache) {
                            cache.modify({
                              fields: {
                                joblines(existingJobLines, { readField }) {
                                  return existingJobLines.filter((jlRef) => record.id !== readField("id", jlRef));
                                }
                              }
                            });
                          }
                        });
                        await axios.post("/job/totalsssu", { id: job.id });
                        if (refetch) refetch();
                      }}
                      icon={<DeleteFilled />}
                    />
                  )}
              </Space>
            )
          }
        ]
      : [])
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState((state) => ({
      ...state,
      filteredInfo: filters,
      sortedInfo: sorter
    }));
    logImEXEvent("joblines_table_change", { pagination, filters, sorter });
  };

  const handleMark = (e) => {
    if (e.key === "clear") {
      setSelectedLines([]);
    } else {
      const markedTypes = [e.key];
      if (e.key === "PAN") markedTypes.push("PAP");
      if (e.key === "PAS") markedTypes.push("PASL");
      setSelectedLines((selectedLines) =>
        _.uniq([
          ...selectedLines,
          ...jobLines.filter((item) => markedTypes.includes(item.part_type) || markedTypes.includes(item.mod_lbr_ty))
        ])
      );
    }
    logImEXEvent("joblines_mark_lines", {});
  };

  const markMenu = {
    onClick: handleMark,
    items: [
      { key: "PAA", label: t("joblines.fields.part_types.PAA") },
      { key: "PAN", label: t("joblines.fields.part_types.PAN") },
      { key: "PAL", label: t("joblines.fields.part_types.PAL") },
      { key: "PAS", label: t("joblines.fields.part_types.PAS") },
      { type: "divider" },
      { key: "LAA", label: t("joblines.fields.lbr_types.LAA") },
      { key: "LAB", label: t("joblines.fields.lbr_types.LAB") },
      { key: "LAD", label: t("joblines.fields.lbr_types.LAD") },
      { key: "LAE", label: t("joblines.fields.lbr_types.LAE") },
      { key: "LAF", label: t("joblines.fields.lbr_types.LAF") },
      { key: "LAG", label: t("joblines.fields.lbr_types.LAG") },
      { key: "LAM", label: t("joblines.fields.lbr_types.LAM") },
      { key: "LAR", label: t("joblines.fields.lbr_types.LAR") },
      { key: "LAS", label: t("joblines.fields.lbr_types.LAS") },
      { key: "LAU", label: t("joblines.fields.lbr_types.LAU") },
      { key: "LA1", label: t("joblines.fields.lbr_types.LA1") },
      { key: "LA2", label: t("joblines.fields.lbr_types.LA2") },
      { key: "LA3", label: t("joblines.fields.lbr_types.LA3") },
      { key: "LA4", label: t("joblines.fields.lbr_types.LA4") },
      { type: "divider" },
      { key: "clear", label: t("general.labels.clear") }
    ]
  };

  return (
    <div>
      <PartsOrderModalContainer />

      <Modal
        open={bulkLocationOpen}
        title={t("joblines.actions.updatelocation")}
        onCancel={closeBulkLocationModal}
        onOk={saveBulkLocation}
        okButtonProps={{
          disabled: jobRO || technician || selectedLineIds.length === 0,
          loading: bulkLocationSaving
        }}
        destroyOnHidden
      >
        <Space orientation="vertical" style={{ width: "100%" }}>
          <Typography.Text type="secondary">
            {t("general.labels.selected")}: {selectedLineIds.length}
          </Typography.Text>

          <Select
            allowClear
            placeholder={t("joblines.fields.location")}
            value={bulkLocation}
            style={{ width: "100%" }}
            popupMatchSelectWidth={false}
            onChange={(val) => setBulkLocation(val ?? null)}
            options={(bodyshop?.md_parts_locations || []).map((loc) => ({ label: loc, value: loc }))}
          />
          <Typography.Text type="secondary">{t("joblines.labels.bulk_location_help")}</Typography.Text>
        </Space>
      </Modal>

      {!technician && (
        <PartsOrderDrawer
          job={job}
          billsQuery={billsQuery}
          handleOnRowClick={handlePartsOrderOnRowClick}
          setPartsReceiveContext={setPartsReceiveContext}
          setTaskUpsertContext={setTaskUpsertContext}
        />
      )}

      <PageHeader
        title={t("jobs.labels.estimatelines")}
        extra={
          <Space wrap>
            <Button onClick={() => refetch()} icon={<SyncOutlined />} />

            {/* Bulk Update Location */}
            <Button
              id="job-lines-bulk-update-location-button"
              disabled={jobRO || technician || selectedLineIds.length === 0}
              onClick={openBulkLocationModal}
            >
              {t("joblines.actions.updatelocation")}
              {selectedLineIds.length > 0 && ` (${selectedLineIds.length})`}
            </Button>

            {job.special_coverage_policy && (
              <Tag color="tomato">
                <Space>
                  <WarningFilled />
                  <span>{t("jobs.labels.specialcoveragepolicy")}</span>
                </Space>
              </Tag>
            )}

            {!isPartsEntry && (
              <JobLineDispatchButton
                selectedLines={selectedLines}
                setSelectedLines={setSelectedLines}
                job={job}
                disabled={technician}
              />
            )}

            {Enhanced_Payroll.treatment === "on" && (
              <JobLineBulkAssignComponent selectedLines={selectedLines} setSelectedLines={setSelectedLines} job={job} />
            )}

            {!isPartsEntry && (
              <Button
                disabled={(job && !job.converted) || (selectedLines.length > 0 ? false : true) || jobRO || technician}
                onClick={() => {
                  setBillEnterContext({
                    actions: { refetch: refetch },
                    context: {
                      disableInvNumber: true,
                      job: { id: job.id },
                      bill: {
                        vendorid: bodyshop.inhousevendorid,
                        invoice_number: "ih",
                        isinhouse: true,
                        date: dayjs(),
                        total: 0,
                        billlines: buildInHouseBillLines(selectedLines)
                      }
                    }
                  });

                  setSelectedLines([]);
                }}
                icon={<HomeOutlined />}
              >
                {t("parts.actions.orderinhouse")}
                {selectedLines.length > 0 && ` (${selectedLines.length})`}
              </Button>
            )}

            <Button
              id="job-lines-order-parts-button"
              disabled={(job && !job.converted) || (selectedLines.length > 0 ? false : true) || jobRO || technician}
              onClick={() => {
                setPartsOrderContext({
                  actions: { refetch: refetch },
                  context: {
                    jobId: job.id,
                    job: job,
                    linesToOrder: selectedLines.map((l) => ({
                      ...l,
                      oem_partno: `${l.oem_partno || ""} ${l.alt_partno ? `(${l.alt_partno})` : ""}`.trim()
                    }))
                  }
                });

                setSelectedLines([]);
              }}
            >
              {t("parts.actions.order")}
              {selectedLines.length > 0 && ` (${selectedLines.length})`}
            </Button>

            {!isPartsEntry && (
              <Button
                icon={<FilterFilled />}
                id="job-lines-filter-parts-only-button"
                onClick={() => {
                  setState((state) => ({
                    ...state,
                    filteredInfo: {
                      ...state.filteredInfo,
                      part_type: ["PAN", "PAC", "PAR", "PAL", "PAA", "PAM", "PAP", "PAS", "PASL", "PAG"]
                    }
                  }));
                }}
              >
                {t("jobs.actions.filterpartsonly")}
              </Button>
            )}

            <Dropdown menu={markMenu} trigger={["click"]}>
              <Button id="repair-data-mark-button">{t("jobs.actions.mark")}</Button>
            </Dropdown>

            {!isPartsEntry && HasRbacAccess({ bodyshop, authLevel, action: "jobs:manual-line" }) && (
              <Button
                disabled={jobRO || technician}
                onClick={() => {
                  setJobLineEditContext({
                    actions: { refetch: refetch },
                    context: { jobid: job.id }
                  });
                }}
              >
                {t("joblines.actions.new")}
              </Button>
            )}

            {!isPartsEntry &&
              InstanceRenderManager({ rome: <JobSendPartPriceChangeComponent job={job} disabled={technician} /> })}

            <JobCreateIOU job={job} selectedJobLines={selectedLines} />

            <Input.Search
              placeholder={t("general.labels.search")}
              onChange={(e) => {
                e.preventDefault();
                setSearchText(e.target.value);
              }}
              enterButton
            />
          </Space>
        }
      />

      <Table
        columns={columns}
        // mobileColumnKeys={["status", "line_desc", "actions", "line_no"]}
        rowKey="id"
        loading={loading}
        pagination={false}
        dataSource={jobLines}
        onChange={handleTableChange}
        scroll={{ x: true }}
        expandable={{
          expandedRowRender: (record) =>
            isPartsEntry ? (
              <JobLinesExpanderSimple jobline={record} jobid={job.id} />
            ) : (
              <JobLinesExpander jobline={record} jobid={job.id} />
            ),
          rowExpandable: () => true,
          expandIcon: ({ expanded, onExpand, record }) =>
            expanded ? (
              <MinusCircleTwoTone onClick={(e) => onExpand(record, e)} />
            ) : (
              <PlusCircleTwoTone
                onClick={(e) => {
                  onExpand(record, e);
                  logImEXEvent("joblines_expander", {});
                }}
              />
            )
        }}
        onRow={(record) => ({
          onDoubleClick: () => {
            logImEXEvent("joblines_double_click_select", {});
            const notMatchingLines = selectedLines.filter((i) => i.id !== record.id);
            notMatchingLines.length !== selectedLines.length
              ? setSelectedLines(notMatchingLines)
              : setSelectedLines([...selectedLines, record]);
          }
        })}
        rowSelection={{
          selectedRowKeys: selectedLines.map((item) => item && item.id),
          onSelectAll: (selected, selectedRows) => {
            setSelectedLines(selectedRows);
          },
          onSelect: (record, selected) => {
            if (selected) {
              setSelectedLines((selectedLines) => _.uniqBy([...selectedLines, record], "id"));
            } else {
              setSelectedLines((selectedLines) => selectedLines.filter((l) => l.id !== record.id));
            }
          }
        }}
      />
    </div>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(JobLinesComponent);
