import { PauseCircleOutlined, PlayCircleOutlined, PrinterFilled } from "@ant-design/icons";
import { PageHeader } from "@ant-design/pro-layout";
import { useMutation, useQuery } from "@apollo/client/react";
import { Button, Descriptions, Drawer, Space } from "antd";
import queryString from "query-string";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";
import { logImEXEvent } from "../../firebase/firebase.utils.js";
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 { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings.js";
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 JobWatcherToggleContainer from "../job-watcher-toggle/job-watcher-toggle.container.jsx";
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" })),
  insertAuditTrail: ({ jobid, operation, type }) =>
    dispatch(
      insertAuditTrail({
        jobid,
        operation,
        type
      })
    )
});
export default connect(mapStateToProps, mapDispatchToProps)(ProductionListDetail);

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

  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"
  });
  const [updateJob] = useMutation(UPDATE_JOB);

  return (
    <Drawer
      title={
        <PageHeader
          title={
            <Space>
              {!technician && scenarioNotificationsOn && <JobWatcherToggleContainer job={theJob} />}
              {theJob.ro_number}
            </Space>
          }
          extra={
            <Space wrap>
              {!technician ? <ProductionRemoveButton jobId={theJob.id} /> : null}
              {!technician && (
                <Button
                  onClick={() => {
                    logImEXEvent("production_toggle_alert");
                    updateJob({
                      variables: {
                        jobId: theJob.id,
                        job: {
                          suspended: !theJob.suspended
                        }
                      }
                    });
                    insertAuditTrail({
                      jobid: theJob.id,
                      operation: AuditTrailMapping.jobsuspend(theJob.suspended ? !theJob.suspended : true),
                      type: "jobsuspend"
                    });
                  }}
                  icon={theJob.suspended ? <PlayCircleOutlined /> : <PauseCircleOutlined />}
                >
                  {theJob.suspended ? t("production.actions.unsuspend") : t("production.actions.suspend")}
                </Button>
              )}
              <Button
                onClick={() => {
                  setPrintCenterContext({
                    actions: { refetch: refetch },
                    context: {
                      id: theJob.id,
                      job: theJob,
                      type: "job"
                    }
                  });
                }}
                icon={<PrinterFilled />}
              >
                {t("jobs.actions.printCenter")}
              </Button>
              {!technician ? <ScoreboardAddButton job={data ? data.jobs_by_pk : {}} /> : null}
            </Space>
          }
        />
      }
      placement="right"
      size="50%"
      onClose={handleClose}
      open={selected}
    >
      {loading && <LoadingSkeleton />}
      {error && <AlertComponent title={JSON.stringify(error)} type="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
                      type={data.jobs_by_pk.ownr_ph1_ty}
                      phone={data.jobs_by_pk.ownr_ph1}
                      jobid={data.jobs_by_pk.id}
                    />
                    <StartChatButton
                      type={data.jobs_by_pk.ownr_ph2_ty}
                      phone={data.jobs_by_pk.ownr_ph2}
                      jobid={data.jobs_by_pk.id}
                    />
                  </>
                ) : (
                  <>
                    <PhoneNumberFormatter type={data.jobs_by_pk.ownr_ph1_ty}>
                      {data.jobs_by_pk.ownr_ph1}
                    </PhoneNumberFormatter>
                    <PhoneNumberFormatter type={data.jobs_by_pk.ownr_ph2_ty}>
                      {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}
                bodyshop={bodyshop}
              />
            </>
          )}
        </div>
      )}
    </Drawer>
  );
}
