import { useQuery } from "@apollo/client";
import { Descriptions, Drawer, Space, PageHeader, Button } from "antd";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { useHistory, useLocation } from "react-router-dom";
import { QUERY_JOB_CARD_DETAILS } from "../../graphql/jobs.queries";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateFormatter } from "../../utils/DateFormatter";
import AlertComponent from "../alert/alert.component";
import StartChatButton from "../chat-open-button/chat-open-button.component";
import JobDetailCardsDocumentsComponent from "../job-detail-cards/job-detail-cards.documents.component";
import JobDetailCardsNotesComponent from "../job-detail-cards/job-detail-cards.notes.component";
import JobDetailCardsPartsComponent from "../job-detail-cards/job-detail-cards.parts.component";
import JobEmployeeAssignments from "../job-employee-assignments/job-employee-assignments.container";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import ProductionRemoveButton from "../production-remove-button/production-remove-button.component";
import JobAtChange from "../job-at-change/job-at-change.component";
import { PrinterFilled } from "@ant-design/icons";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { setModalContext } from "../../redux/modals/modals.actions";
import ScoreboardAddButton from "../job-scoreboard-add-button/job-scoreboard-add-button.component";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  setPrintCenterContext: (context) =>
    dispatch(setModalContext({ context: context, modal: "printCenter" })),
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ProductionListDetail);

export function ProductionListDetail({
  bodyshop,
  jobs,
  setPrintCenterContext,
}) {
  const search = queryString.parse(useLocation().search);
  const history = useHistory();
  const { selected } = search;

  const { t } = useTranslation();
  const theJob = jobs.find((j) => j.id === selected) || {};

  const handleClose = () => {
    delete search.selected;
    history.push({ search: queryString.stringify(search) });
  };
  const { loading, error, data, refetch } = useQuery(QUERY_JOB_CARD_DETAILS, {
    variables: { id: selected },
    skip: !selected,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
  });

  return (
    <Drawer
      title={
        <PageHeader
          title={theJob.ro_number}
          extra={
            <Space wrap>
              <ProductionRemoveButton jobId={theJob.id} />{" "}
              <Button
                onClick={() => {
                  setPrintCenterContext({
                    actions: { refetch: refetch },
                    context: {
                      id: theJob.id,
                      job: theJob,
                      type: "job",
                    },
                  });
                }}
              >
                <PrinterFilled />
                {t("jobs.actions.printCenter")}
              </Button>
              <ScoreboardAddButton job={data ? data.jobs_by_pk : {}} />
            </Space>
          }
        />
      }
      placement="right"
      width={"33%"}
      onClose={handleClose}
      visible={selected}
    >
      {loading && <LoadingSkeleton />}
      {error && <AlertComponent error={JSON.stringify(error)} />}
      {!loading && data && (
        <div>
          <JobEmployeeAssignments job={data.jobs_by_pk} refetch={refetch} />
          <Descriptions bordered column={1}>
            <Descriptions.Item label={t("jobs.fields.ro_number")}>
              {theJob.ro_number || ""}
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.alt_transport")}>
              <Space>
                {data.jobs_by_pk.alt_transport || ""}
                <JobAtChange event={{ job: data.jobs_by_pk }} />
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.clm_no")}>
              {theJob.clm_no || ""}
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.ins_co_nm")}>
              {theJob.ins_co_nm || ""}
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.owner")}>
              <OwnerNameDisplay ownerObject={theJob} />
              <StartChatButton
                phone={data.jobs_by_pk.ownr_ph1}
                jobid={data.jobs_by_pk.id}
              />
              <StartChatButton
                phone={data.jobs_by_pk.ownr_ph2}
                jobid={data.jobs_by_pk.id}
              />
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.vehicle")}>
              {`${theJob.v_model_yr || ""} ${theJob.v_color || ""} ${
                theJob.v_make_desc || ""
              } ${theJob.v_model_desc || ""}`}
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.clm_total")}>
              <CurrencyFormatter>{theJob.clm_total}</CurrencyFormatter>
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.actual_in")}>
              <DateFormatter>{theJob.actual_in}</DateFormatter>
            </Descriptions.Item>
            <Descriptions.Item label={t("jobs.fields.scheduled_completion")}>
              <DateFormatter>{theJob.scheduled_completion}</DateFormatter>
            </Descriptions.Item>
          </Descriptions>

          <JobDetailCardsPartsComponent
            loading={loading}
            data={data ? data.jobs_by_pk : null}
          />

          <JobDetailCardsNotesComponent
            loading={loading}
            data={data ? data.jobs_by_pk : null}
          />
          {!bodyshop.uselocalmediaserver && (
            <JobDetailCardsDocumentsComponent
              loading={loading}
              data={data ? data.jobs_by_pk : null}
            />
          )}
        </div>
      )}
    </Drawer>
  );
}
