import { useQuery } from "@apollo/client";
import { Card, Divider, Drawer, Grid } from "antd";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { Link, useHistory, useLocation } from "react-router-dom";
import { QUERY_PARTS_QUEUE_CARD_DETAILS } from "../../graphql/jobs.queries";
import AlertComponent from "../alert/alert.component";
import JobsDetailHeader from "../jobs-detail-header/jobs-detail-header.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import PartsQueueJobLinesComponent from "./parts-queue-job-lines.component";

export default function PartsQueueDetailCard() {
  const selectedBreakpoint = Object.entries(Grid.useBreakpoint())
    .filter((screen) => !!screen[1])
    .slice(-1)[0];

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

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

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

  return (
    <Drawer
      visible={!!selected}
      destroyOnClose
      width={drawerPercentage}
      placement="right"
      onClose={handleDrawerClose}
    >
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent message={error.message} type="error" /> : null}
      {data ? (
        <Card
          title={
            <Link to={`/manage/jobs/${data.jobs_by_pk.id}`}>
              {data.jobs_by_pk.ro_number || t("general.labels.na")}
            </Link>
          }
        >
          <JobsDetailHeader job={data ? data.jobs_by_pk : null} />
          <Divider type="horizontal" />
          <PartsQueueJobLinesComponent
            jobLines={data.jobs_by_pk ? data.jobs_by_pk.joblines : null}
          />
        </Card>
      ) : null}
    </Drawer>
  );
}
