import { PrinterFilled } from "@ant-design/icons";
import { useQuery } from "@apollo/client";
import { Button, Divider, Drawer, Grid, Tabs } from "antd";
import { PageHeader } from "@ant-design/pro-layout";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { GET_JOB_BY_PK } from "../../graphql/jobs.queries";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import JobLinesContainer from "../job-detail-lines/job-lines.container";
import JobsDetailHeader from "../jobs-detail-header/jobs-detail-header.component";
import JobsDocumentsGalleryContainer from "../jobs-documents-gallery/jobs-documents-gallery.container";
import JobsDocumentsLocalGallery from "../jobs-documents-local-gallery/jobs-documents-local-gallery.container";
import JobNotesContainer from "../jobs-notes/jobs-notes.container";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";

const mapStateToProps = createStructuredSelector({ bodyshop: selectBodyshop });

const mapDispatchToProps = (dispatch) => ({
  setPrintCenterContext: (context) => dispatch(setModalContext({ context: context, modal: "printCenter" }))
});

// const colBreakPoints = {
//   xs: {
//     span: 24,
//   },
//   sm: {
//     span: 8,
//   },
// };

export function TechLookupJobsDrawer({ bodyshop, setPrintCenterContext }) {
  const selectedBreakpoint = Object.entries(Grid.useBreakpoint())
    .filter((screen) => !!screen[1])
    .slice(-1)[0];

  const bpoints = {
    xs: "100%",
    sm: "100%",
    md: "100%",
    lg: "100%",
    xl: "90%",
    xxl: "85%"
  };
  const drawerPercentage = selectedBreakpoint ? bpoints[selectedBreakpoint[0]] : "100%";

  const searchParams = queryString.parse(useLocation().search);
  const { selected } = searchParams;
  const history = useNavigate();
  const { loading, error, data, refetch } = useQuery(GET_JOB_BY_PK, {
    variables: { id: selected },
    skip: !selected,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const { t } = useTranslation();
  const handleDrawerClose = () => {
    delete searchParams.selected;
    history({
      search: queryString.stringify({
        ...searchParams
      })
    });
  };

  return (
    <Drawer open={!!selected} destroyOnClose width={drawerPercentage} placement="right" onClose={handleDrawerClose}>
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent message={error.message} type="error" /> : null}
      {data ? (
        <PageHeader
          onBack={() => window.history.back()}
          title={data.jobs_by_pk.ro_number || t("general.labels.na")}
          extra={
            <Button
              onClick={() => {
                setPrintCenterContext({
                  actions: { refetch: refetch },
                  context: {
                    id: data.jobs_by_pk.id,
                    job: data.jobs_by_pk,
                    type: "job"
                  }
                });
              }}
            >
              <PrinterFilled />
              {t("jobs.actions.printCenter")}
            </Button>
          }
        >
          <JobsDetailHeader job={data.jobs_by_pk} disabled />
          <Divider type="horizontal" />
          <Tabs
            size="large"
            defaultActiveKey="lines"
            items={[
              {
                key: "lines",
                label: t("jobs.labels.lines"),
                children: (
                  <JobLinesContainer
                    jobId={selected}
                    joblines={data.jobs_by_pk.joblines}
                    job={data.jobs_by_pk}
                    refetch={refetch}
                  />
                )
              },
              {
                key: "documents",
                label: t("jobs.labels.documents"),
                children: bodyshop.uselocalmediaserver ? (
                  <JobsDocumentsLocalGallery job={data ? data.jobs_by_pk : null} />
                ) : (
                  <JobsDocumentsGalleryContainer jobId={searchParams.selected} />
                )
              },
              {
                key: "notes",
                label: t("jobs.labels.notes"),
                children: <JobNotesContainer jobId={searchParams.selected} />
              }
            ]}
          />
        </PageHeader>
      ) : null}
    </Drawer>
  );
}

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