import { PrinterFilled } from "@ant-design/icons";
import { useQuery } from "@apollo/react-hooks";
import { Button, Col, Drawer, Grid, PageHeader, Row, Tag, Space } from "antd";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useHistory, useLocation } from "react-router-dom";
import { QUERY_JOB_CARD_DETAILS } from "../../graphql/jobs.queries";
import { setModalContext } from "../../redux/modals/modals.actions";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import OwnerTagPopoverComponent from "../owner-tag-popover/owner-tag-popover.component";
import VehicleTagPopoverComponent from "../vehicle-tag-popover/vehicle-tag-popover.component";
import JobDetailCardsDamageComponent from "./job-detail-cards.damage.component";
import JobDetailCardsDatesComponent from "./job-detail-cards.dates.component";
import JobDetailCardsDocumentsComponent from "./job-detail-cards.documents.component";
import JobDetailCardsInsuranceComponent from "./job-detail-cards.insurance.component";
import JobDetailCardsNotesComponent from "./job-detail-cards.notes.component";
import JobDetailCardsPartsComponent from "./job-detail-cards.parts.component";
import JobDetailCardsTotalsComponent from "./job-detail-cards.totals.component";

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

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

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

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

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

  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 ? (
        <PageHeader
          ghost={true}
          tags={[
            <OwnerTagPopoverComponent key="owner" job={data.jobs_by_pk} />,
            <VehicleTagPopoverComponent key="vehicle" job={data.jobs_by_pk} />,
            <Tag
              color="#f50"
              key="production"
              style={{ display: data.jobs_by_pk.inproduction ? "" : "none" }}
            >
              {t("jobs.labels.inproduction")}
            </Tag>,
          ]}
          title={
            <Link to={`/manage/jobs/${data.jobs_by_pk.id}`}>
              {data.jobs_by_pk.ro_number
                ? `${t("jobs.fields.ro_number")} ${data.jobs_by_pk.ro_number}`
                : `${t("jobs.fields.est_number")} ${
                    data.jobs_by_pk.est_number
                  }`}
            </Link>
          }
          subTitle={data.jobs_by_pk.status}
          extra={
            <Space>
              <Button
                onClick={() => {
                  setPrintCenterContext({
                    actions: { refetch: refetch },
                    context: {
                      id: data.jobs_by_pk.id,
                      type: "job",
                    },
                  });
                }}
              >
                <PrinterFilled />
                {t("jobs.actions.printCenter")}
              </Button>
              <Link to={`/manage/jobs/${data.jobs_by_pk.id}?tab=repairdata`}>
                <Button>{t("parts.actions.order")}</Button>
              </Link>
            </Space>
          }
        >
          <Row gutter={[16, 16]}>
            <Col {...colBreakPoints}>
              <JobDetailCardsInsuranceComponent
                loading={loading}
                data={data ? data.jobs_by_pk : null}
              />
            </Col>
            <Col {...colBreakPoints}>
              <JobDetailCardsTotalsComponent
                loading={loading}
                data={data ? data.jobs_by_pk : null}
              />
            </Col>
            <Col {...colBreakPoints}>
              <JobDetailCardsDatesComponent
                loading={loading}
                data={data ? data.jobs_by_pk : null}
              />
            </Col>
            <Col {...colBreakPoints}>
              <JobDetailCardsPartsComponent
                loading={loading}
                data={data ? data.jobs_by_pk : null}
              />
            </Col>
            <Col {...colBreakPoints}>
              <JobDetailCardsNotesComponent
                loading={loading}
                data={data ? data.jobs_by_pk : null}
              />
            </Col>
            <Col {...colBreakPoints}>
              <JobDetailCardsDocumentsComponent
                loading={loading}
                data={data ? data.jobs_by_pk : null}
              />
            </Col>
            <Col {...colBreakPoints}>
              <JobDetailCardsDamageComponent
                loading={loading}
                data={data ? data.jobs_by_pk : null}
              />
            </Col>
          </Row>
        </PageHeader>
      ) : null}
    </Drawer>
  );
}
export default connect(null, mapDispatchToProps)(JobDetailCards);
