import { PrinterFilled } from "@ant-design/icons";
import { useQuery } from "@apollo/client";
import { Button, Card, Col, Divider, Drawer, Grid, Row, Space } from "antd";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { QUERY_JOB_CARD_DETAILS } 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 JobSyncButton from "../job-sync-button/job-sync-button.component";
import JobsDetailHeader from "../jobs-detail-header/jobs-detail-header.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.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 mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

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

const span = {
  lg: { span: 24 },
  xl: { span: 12 },
  xxl: { span: 8 }
};

export function JobDetailCards({ bodyshop, setPrintCenterContext }) {
  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 = useNavigate();
  const { loading, error, data, refetch } = useQuery(QUERY_JOB_CARD_DETAILS, {
    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 ? (
        <Card
          title={
            <Link to={`/manage/jobs/${data.jobs_by_pk.id}`}>{data.jobs_by_pk.ro_number || t("general.labels.na")}</Link>
          }
          extra={
            <Space wrap>
              <JobSyncButton job={data.jobs_by_pk} />

              <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>
              <Link to={`/manage/jobs/${data.jobs_by_pk.id}?tab=repairdata`}>
                <Button>{t("parts.actions.order")}</Button>
              </Link>
            </Space>
          }
        >
          <JobsDetailHeader job={data ? data.jobs_by_pk : null} />
          <Divider type="horizontal" />
          <Row gutter={[16, 16]}>
            <Col {...span}>
              <JobDetailCardsInsuranceComponent loading={loading} data={data ? data.jobs_by_pk : null} />
            </Col>
            <Col {...span}>
              <JobDetailCardsTotalsComponent loading={loading} data={data ? data.jobs_by_pk : null} />
            </Col>
            <Col {...span}>
              <JobDetailCardsDatesComponent loading={loading} data={data ? data.jobs_by_pk : null} />
            </Col>
            <Col {...span}>
              <JobDetailCardsNotesComponent loading={loading} data={data ? data.jobs_by_pk : null} />
            </Col>
            {!bodyshop.uselocalmediaserver && (
              <Col {...span}>
                <JobDetailCardsDocumentsComponent loading={loading} data={data ? data.jobs_by_pk : null} />
              </Col>
            )}
            <Col {...span}>
              <JobDetailCardsDamageComponent loading={loading} data={data ? data.jobs_by_pk : null} />
            </Col>
            <Col span={24}>
              <JobDetailCardsPartsComponent loading={loading} data={data ? data.jobs_by_pk : null} />
            </Col>
          </Row>
        </Card>
      ) : null}
    </Drawer>
  );
}

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