import { useQuery } from "@apollo/client/react";
import { Card, Divider, Drawer, Grid } from "antd";
import queryString from "query-string";
import { useTranslation } from "react-i18next";
import { Link, useLocation, useNavigate } 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";
import { logImEXEvent } from "../../firebase/firebase.utils";

export default function PartsQueueDetailCard() {
  const screens = Grid.useBreakpoint();
  
  const bpoints = {
    xs: "100%",
    sm: "100%",
    md: "100%",
    lg: "75%",
    xl: "75%",
    xxl: "60%"
  };
  
  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 searchParams = queryString.parse(useLocation().search);
  const { selected } = searchParams;
  const history = useNavigate();
  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;
    logImEXEvent("parts_queue_drawer", {});

    history({
      search: queryString.stringify({
        ...searchParams
      })
    });
  };

  return (
    <Drawer open={!!selected} destroyOnHidden size={drawerPercentage} placement="right" onClose={handleDrawerClose}>
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent title={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 orientation="horizontal" />
          <PartsQueueJobLinesComponent jobLines={data.jobs_by_pk ? data.jobs_by_pk.joblines : null} />
        </Card>
      ) : null}
    </Drawer>
  );
}
