import { PrinterFilled } from "@ant-design/icons";
import { useQuery } from "@apollo/client/react";
import { Button, Divider, Drawer, Grid, Tabs } from "antd";
import { PageHeader } from "@ant-design/pro-layout";
import queryString from "query-string";
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" }))
});

export function TechLookupJobsDrawer({ bodyshop, setPrintCenterContext }) {
  const screens = Grid.useBreakpoint();

  const bpoints = {
    xs: "100%",
    sm: "100%",
    md: "100%",
    lg: "100%",
    xl: "90%",
    xxl: "90%"
  };

  let drawerPercentage = "100%";
  if (screens.xxl) drawerPercentage = bpoints.xxl;
  else if (screens.xl) drawerPercentage = bpoints.xl;
  else if (screens.lg) drawerPercentage = bpoints.lg;
  else if (screens.md) drawerPercentage = bpoints.md;
  else if (screens.sm) drawerPercentage = bpoints.sm;
  else if (screens.xs) drawerPercentage = bpoints.xs;

  const location = useLocation();
  const history = useNavigate();

  // Parse once per render; do not mutate this object later.
  const searchParams = queryString.parse(location.search);
  const selected = searchParams?.selected;

  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 = () => {
    // Immutable omit (no delete/mutation)
    const { selected, ...rest } = searchParams || {};
    void selected;
    history({
      search: queryString.stringify(rest)
    });
  };

  return (
    <Drawer open={!!selected} destroyOnHidden size={drawerPercentage} placement="right" onClose={handleDrawerClose}>
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent title={error.message} type="error" /> : null}

      {data ? (
        <PageHeader
          title={data.jobs_by_pk.ro_number || t("general.labels.na")}
          extra={
            <Button
              icon={<PrinterFilled />}
              onClick={() => {
                setPrintCenterContext({
                  actions: { refetch: refetch },
                  context: {
                    id: data.jobs_by_pk.id,
                    job: data.jobs_by_pk,
                    type: "job"
                  }
                });
              }}
            >
              {t("jobs.actions.printCenter")}
            </Button>
          }
        >
          <JobsDetailHeader job={data.jobs_by_pk} disabled />
          <Divider orientation="horizontal" />
          <Tabs
            width="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={selected} />
                )
              },
              {
                key: "notes",
                label: t("jobs.labels.notes"),
                children: <JobNotesContainer jobId={selected} />
              }
            ]}
          />
        </PageHeader>
      ) : null}
    </Drawer>
  );
}

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