import { PrinterFilled } from "@ant-design/icons";
import { useQuery } from "@apollo/client";
import { Button, Descriptions, Drawer, Space } from "antd";
import { PageHeader } from "@ant-design/pro-layout";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { 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 { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateFormatter } from "../../utils/DateFormatter";
import PhoneNumberFormatter from "../../utils/PhoneFormatter";
import AlertComponent from "../alert/alert.component";
import StartChatButton from "../chat-open-button/chat-open-button.component";
import JobAtChange from "../job-at-change/job-at-change.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 CardTemplate from "../job-detail-cards/job-detail-cards.template.component";
import JobEmployeeAssignments from "../job-employee-assignments/job-employee-assignments.container";
import ScoreboardAddButton from "../job-scoreboard-add-button/job-scoreboard-add-button.component";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import ProductionRemoveButton from "../production-remove-button/production-remove-button.component";

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

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

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

  const handleClose = () => {
    delete search.selected;
    history({ 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>
              {!technician ? <ProductionRemoveButton jobId={theJob.id} /> : null}
              <Button
                onClick={() => {
                  setPrintCenterContext({
                    actions: { refetch: refetch },
                    context: {
                      id: theJob.id,
                      job: theJob,
                      type: "job"
                    }
                  });
                }}
              >
                <PrinterFilled />
                {t("jobs.actions.printCenter")}
              </Button>
              {!technician ? <ScoreboardAddButton job={data ? data.jobs_by_pk : {}} /> : null}
            </Space>
          }
        />
      }
      placement="right"
      width={"50%"}
      onClose={handleClose}
      open={selected}
    >
      {loading && <LoadingSkeleton />}
      {error && <AlertComponent error={JSON.stringify(error)} />}
      {!loading && data && (
        <div>
          <CardTemplate title={t("jobs.labels.employeeassignments")} loading={loading}>
            <JobEmployeeAssignments job={data.jobs_by_pk} refetch={refetch} />
          </CardTemplate>
          <div style={{ height: "8px" }} />
          <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 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")}>
              <Space>
                <OwnerNameDisplay ownerObject={theJob} />
                {!technician ? (
                  <>
                    <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} />
                  </>
                ) : (
                  <>
                    <PhoneNumberFormatter>{data.jobs_by_pk.ownr_ph1}</PhoneNumberFormatter>
                    <PhoneNumberFormatter>{data.jobs_by_pk.ownr_ph2}</PhoneNumberFormatter>
                  </>
                )}
              </Space>
            </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>
          <div style={{ height: "8px" }} />
          <JobDetailCardsPartsComponent loading={loading} data={data ? data.jobs_by_pk : null} />
          <div style={{ height: "8px" }} />
          <JobDetailCardsNotesComponent loading={loading} data={data ? data.jobs_by_pk : null} />
          {!bodyshop.uselocalmediaserver && (
            <>
              <div style={{ height: "8px" }} />
              <JobDetailCardsDocumentsComponent loading={loading} data={data ? data.jobs_by_pk : null} />
            </>
          )}
        </div>
      )}
    </Drawer>
  );
}
