import { PauseCircleOutlined, PlayCircleOutlined, PrinterFilled } from "@ant-design/icons";
import { useMutation, useQuery } from "@apollo/client/react";
import { Button, Card, Col, Divider, Drawer, Grid, Row, Space } from "antd";
import queryString from "query-string";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";

import { logImEXEvent } from "../../firebase/firebase.utils";
import { QUERY_JOB_CARD_DETAILS, UPDATE_JOB } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions.js";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings.js";
import AlertComponent from "../alert/alert.component";
import JobSyncButton from "../job-sync-button/job-sync-button.component";
import JobWatcherToggleContainer from "../job-watcher-toggle/job-watcher-toggle.container.jsx";
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"
      })
    ),
  insertAuditTrail: ({ jobid, operation, type }) =>
    dispatch(
      insertAuditTrail({
        jobid,
        operation,
        type
      })
    )
});

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

export function JobDetailCards({ bodyshop, setPrintCenterContext, insertAuditTrail }) {
  const { scenarioNotificationsOn } = useSocket();
  const [updateJob] = useMutation(UPDATE_JOB);
  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: "75%"
  };
  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} destroyOnHidden width={drawerPercentage} placement="right" onClose={handleDrawerClose}>
      {loading ? <LoadingSpinner /> : null}
      {error ? <AlertComponent title={error.message} type="error" /> : null}
      {data ? (
        <Card
          title={
            <Space>
              {scenarioNotificationsOn && <JobWatcherToggleContainer job={data.jobs_by_pk} />}
              <Link to={`/manage/jobs/${data.jobs_by_pk.id}`}>
                {data.jobs_by_pk.ro_number || t("general.labels.na")}
              </Link>
            </Space>
          }
          extra={
            <Space wrap>
              <JobSyncButton job={data.jobs_by_pk} />
              <Button
                onClick={() => {
                  logImEXEvent("production_toggle_alert");
                  updateJob({
                    variables: {
                      jobId: data.jobs_by_pk.id,
                      job: {
                        suspended: !data.jobs_by_pk.suspended
                      }
                    }
                  });
                  insertAuditTrail({
                    jobid: data.jobs_by_pk.id,
                    operation: AuditTrailMapping.jobsuspend(
                      data.jobs_by_pk.suspended ? !data.jobs_by_pk.suspended : true
                    ),
                    type: "jobsuspend"
                  });
                }}
                icon={data.jobs_by_pk.suspended ? <PlayCircleOutlined /> : <PauseCircleOutlined />}
              >
                {data.jobs_by_pk.suspended ? t("production.actions.unsuspend") : t("production.actions.suspend")}
              </Button>
              <Button
                onClick={() => {
                  setPrintCenterContext({
                    actions: { refetch: refetch },
                    context: {
                      id: data.jobs_by_pk.id,
                      job: data.jobs_by_pk,
                      type: "job"
                    }
                  });
                }}
                icon={<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 orientation="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}
                  bodyshop={bodyshop}
                />
              </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);
