import Icon, {
  BarsOutlined,
  CalendarFilled,
  DollarCircleOutlined,
  FileImageFilled,
  HistoryOutlined,
  PrinterFilled,
  SyncOutlined,
  ToolFilled
} from "@ant-design/icons";
import { PageHeader } from "@ant-design/pro-layout";
import { useQuery } from "@apollo/client/react";
import { Badge, Button, Divider, Form, Space, Tabs } from "antd";
import Axios from "axios";
import _ from "lodash";
import queryString from "query-string";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { FaHardHat, FaRegStickyNote, FaShieldAlt, FaTasks } from "react-icons/fa";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import FormFieldsChanged from "../../components/form-fields-changed-alert/form-fields-changed-alert.component";
import JobAuditTrail from "../../components/job-audit-trail/job-audit-trail.component";
import JobsLinesContainer from "../../components/job-detail-lines/job-lines.container";
import JobLifecycleComponent from "../../components/job-lifecycle/job-lifecycle.component";
import JobLineUpsertModalContainer from "../../components/job-lines-upsert-modal/job-lines-upsert-modal.container";
import JobProfileDataWarning from "../../components/job-profile-data-warning/job-profile-data-warning.component";
import JobReconciliationModal from "../../components/job-reconciliation-modal/job-reconciliation.modal.container";
import JobSyncButton from "../../components/job-sync-button/job-sync-button.component";
import JobWatcherToggleContainer from "../../components/job-watcher-toggle/job-watcher-toggle.container.jsx";
import JobsChangeStatus from "../../components/jobs-change-status/jobs-change-status.component";
import JobsConvertButton from "../../components/jobs-convert-button/jobs-convert-button.component";
import JobsDetailDatesComponent from "../../components/jobs-detail-dates/jobs-detail-dates.component";
import JobsDetailGeneral from "../../components/jobs-detail-general/jobs-detail-general.component";
import JobsDetailHeaderActions from "../../components/jobs-detail-header-actions/jobs-detail-header-actions.component";
import JobsDetailHeader from "../../components/jobs-detail-header/jobs-detail-header.component";
import JobsDetailLaborContainer from "../../components/jobs-detail-labor/jobs-detail-labor.container";
import JobsDetailPliContainer from "../../components/jobs-detail-pli/jobs-detail-pli.container";
import JobsDetailRates from "../../components/jobs-detail-rates/jobs-detail-rates.component";
import JobsDetailTotals from "../../components/jobs-detail-totals/jobs-detail-totals.component";
import JobsDocumentsGalleryContainer from "../../components/jobs-documents-gallery/jobs-documents-gallery.container";
import JobsDocumentsLocalGallery from "../../components/jobs-documents-local-gallery/jobs-documents-local-gallery.container";
import JobNotesContainer from "../../components/jobs-notes/jobs-notes.container";
import LockWrapperComponent from "../../components/lock-wrapper/lock-wrapper.component.jsx";
import ScheduleJobModalContainer from "../../components/schedule-job-modal/schedule-job-modal.container";
import TaskListContainer from "../../components/task-list/task-list.container.jsx";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";
import { QUERY_PARTS_BILLS_BY_JOBID } from "../../graphql/bills.queries.js";
import { QUERY_JOB_TASKS_PAGINATED } from "../../graphql/tasks.queries.js";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { DateTimeFormat } from "../../utils/DateFormatter";
import dayjs from "../../utils/day";
import UndefinedToNull from "../../utils/undefinedtonull";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly
});
const mapDispatchToProps = (dispatch) => ({
  setPrintCenterContext: (context) =>
    dispatch(
      setModalContext({
        context: context,
        modal: "printCenter"
      })
    ),
  insertAuditTrail: ({ jobid, operation, type }) =>
    dispatch(
      insertAuditTrail({
        jobid,
        operation,
        type
      })
    )
});

export function JobsDetailPage({
  bodyshop,
  setPrintCenterContext,
  jobRO,
  job,
  mutationUpdateJob,
  insertAuditTrail,
  refetch
}) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const history = useNavigate();
  const [loading, setLoading] = useState(false);
  const search = queryString.parse(useLocation().search);
  const formItemLayout = {
    layout: "vertical"
  };
  const billsQuery = useQuery(QUERY_PARTS_BILLS_BY_JOBID, {
    variables: { jobid: job.id },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });
  const notification = useNotification();
  const { scenarioNotificationsOn } = useSocket();

  useEffect(() => {
    //form.setFieldsValue(transormJobToForm(job));
    form.resetFields();
  }, [form, job]);

  //useKeyboardSaveShortcut(form.submit);

  const handleBillOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        search.billid = record.id;
        history({ search: queryString.stringify(search) });
      }
    } else {
      delete search.billid;
      history({ search: queryString.stringify(search) });
    }
  };

  const handlePartsOrderOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        search.partsorderid = record.id;
        history({ search: queryString.stringify(search) });
      }
    } else {
      delete search.partsorderid;
      history({ search: queryString.stringify(search) });
    }
  };

  const handlePartsDispatchOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        search.partsdispatchid = record.id;
        history.push({ search: queryString.stringify(search) });
      }
    } else {
      delete search.partsdispatchid;
      history.push({ search: queryString.stringify(search) });
    }
  };

  const handleFinish = async (values) => {
    setLoading(true);

    const result = await mutationUpdateJob({
      variables: {
        jobId: job.id,
        job: {
          ...UndefinedToNull(values, ["alt_transport", "category", "referral_source"]),
          // The union and spread is required to keep values coming in from the estimating system that aren't displayed.
          parts_tax_rates: _.union(Object.keys(job.parts_tax_rates), Object.keys(values.parts_tax_rates || {})).reduce(
            (acc, val) => {
              acc[val] = {
                ...job.parts_tax_rates[val],
                ...values.parts_tax_rates?.[val]
              };
              return acc;
            },
            {}
          ),
          materials: _.union(Object.keys(job.materials), Object.keys(values.materials || {})).reduce((acc, val) => {
            acc[val] = {
              ...job.materials[val],
              ...values.materials?.[val]
            };
            return acc;
          }, {}),
          cieca_pfl: _.union(Object.keys(job.cieca_pfl), Object.keys(values.cieca_pfl || {})).reduce((acc, val) => {
            acc[val] = {
              ...job.cieca_pfl[val],
              ...values.cieca_pfl?.[val]
            };
            return acc;
          }, {}),
          cieca_pfo: { ...job.cieca_pfo, ...values.cieca_pfo }
        }
      }
    });
    try {
      const newTotals = await Axios.post("/job/totalsssu", {
        id: job.id
      });

      if (newTotals.status !== 200 || result.errors) {
        notification.error({
          title: t("jobs.errors.totalscalc")
        });
      } else {
        notification.success({
          title: t("jobs.successes.savetitle")
        });
        const changedAuditFields = form.getFieldsValue(
          [
            "scheduled_in",
            "actual_in",
            "scheduled_completion",
            "actual_completion",
            "scheduled_delivery",
            "actual_delivery",
            "date_invoiced",
            "ins_co_nm",
            "ded_amt",
            "ded_status",
            "date_exported",
            "special_coverage_policy",
            "ca_gst_registrant",
            "ca_bc_pvrt",
            "scheduled_in",
            "rate_la1",
            "rate_la2",
            "rate_la3",
            "rate_la4",
            "rate_laa",
            "rate_lab",
            "rate_lad",
            "rate_lae",
            "rate_laf",
            "rate_lag",
            "rate_lam",
            "rate_lar",
            "rate_las",
            "rate_lau",
            "rate_ma2s",
            "rate_ma2t",
            "rate_ma3s",
            "rate_mabl",
            "rate_macs",
            "rate_mapa",
            "rate_mahw",
            "rate_mash",
            "rate_matd",
            "flat_rate_ats",
            "state_tax_rate",
            "tax_lbr_rt",
            "tax_shop_mat_rt",
            "tax_paint_mat_rt",
            "tax_sub_rt"
          ],
          (meta) => meta && meta.touched
        );

        Object.keys(changedAuditFields).forEach((key) => {
          insertAuditTrail({
            jobid: job.id,
            operation: AuditTrailMapping.jobfieldchange(
              key,
              changedAuditFields[key] instanceof dayjs
                ? DateTimeFormat(changedAuditFields[key])
                : changedAuditFields[key]
            ),
            type: "jobfieldchange"
          });
        });

        await refetch();
        form.setFieldsValue(transformJobToForm(job));
        form.resetFields();
      }
    } catch {
      notification.error({
        title: t("jobs.errors.totalscalc")
      });
    } finally {
      setLoading(false);
    }
  };

  const menuExtra = (
    <Space wrap>
      <Button
        icon={<SyncOutlined />}
        onClick={() => {
          refetch();
        }}
        key="refresh"
      >
        {t("general.labels.refresh")}
      </Button>
      <JobsChangeStatus job={job} />
      <JobSyncButton job={job} />
      <Button
        icon={<PrinterFilled />}
        onClick={() => {
          setPrintCenterContext({
            actions: { refetch: refetch },
            context: {
              id: job.id,
              job: job,
              type: "job"
            }
          });
        }}
        key="printing"
      >
        {t("jobs.actions.printCenter")}
      </Button>
      <JobsConvertButton job={job} refetch={refetch} parentFormIsFieldsTouched={form.isFieldsTouched} />
      <JobsDetailHeaderActions key="actions" job={job} refetch={refetch} />
      <Button type="primary" loading={loading} disabled={jobRO} onClick={() => form.submit()}>
        {t("general.actions.save")}
      </Button>
    </Space>
  );

  return (
    <div>
      <ScheduleJobModalContainer />
      <JobReconciliationModal />
      <JobLineUpsertModalContainer />
      <Form
        form={form}
        name="JobDetailForm"
        onFinish={handleFinish}
        {...formItemLayout}
        autoComplete={"off"}
        initialValues={transformJobToForm(job)}
      >
        <PageHeader
          // onBack={() => window.history.back()}
          id="job-detail-header"
          title={
            <Space>
              {scenarioNotificationsOn && <JobWatcherToggleContainer job={job} />}
              <span id="job-ro_number">{job.ro_number || t("general.labels.na")}</span>
            </Space>
          }
          extra={menuExtra}
        />
        <JobsDetailHeader job={job} />
        <Divider orientation="horizontal" />
        <JobProfileDataWarning job={job} />
        <FormFieldsChanged form={form} />
        <Tabs
          defaultActiveKey={search.tab}
          onChange={(key) => history({ search: `?tab=${key}` })}
          tabBarStyle={{ fontWeight: "bold", borderBottom: "10px" }}
          items={[
            {
              key: "general",
              icon: <Icon component={FaShieldAlt} />,
              id: "job-details-general",
              label: t("menus.jobsdetail.general"),
              forceRender: true,
              children: <JobsDetailGeneral job={job} form={form} />
            },
            {
              key: "repairdata",
              icon: <BarsOutlined />,
              id: "job-details-repairdata",
              label: t("menus.jobsdetail.repairdata"),
              forceRender: true,
              children: (
                <JobsLinesContainer
                  job={job}
                  joblines={job.joblines}
                  billsQuery={billsQuery}
                  handleBillOnRowClick={handleBillOnRowClick}
                  handlePartsOrderOnRowClick={handlePartsOrderOnRowClick}
                  handlePartsDispatchOnRowClick={handlePartsDispatchOnRowClick}
                  refetch={refetch}
                  form={form}
                />
              )
            },
            {
              key: "rates",
              icon: <DollarCircleOutlined />,
              id: "job-details-rates",
              label: t("menus.jobsdetail.rates"),
              forceRender: true,
              children: <JobsDetailRates job={job} form={form} />
            },
            {
              key: "totals",
              id: "job-details-totals",
              icon: <DollarCircleOutlined />,
              label: t("menus.jobsdetail.totals"),
              children: <JobsDetailTotals job={job} refetch={refetch} />
            },
            {
              key: "partssublet",
              id: "job-details-partssublet",
              icon: <ToolFilled />,
              label: t("menus.jobsdetail.partssublet"),
              children: (
                <JobsDetailPliContainer
                  job={job}
                  billsQuery={billsQuery}
                  handleBillOnRowClick={handleBillOnRowClick}
                  handlePartsOrderOnRowClick={handlePartsOrderOnRowClick}
                  handlePartsDispatchOnRowClick={handlePartsDispatchOnRowClick}
                />
              )
            },

            {
              key: "labor",
              id: "job-details-labor",
              icon: <Icon component={FaHardHat} style={{ marginRight: 15 }} />,
              label: (
                <LockWrapperComponent featureName="timetickets">{t("menus.jobsdetail.labor")}</LockWrapperComponent>
              ),
              children: <JobsDetailLaborContainer job={job} jobId={job.id} />
            },
            {
              key: "lifecycle",
              icon: <BarsOutlined />,
              id: "job-details-lifecycle",
              label: (
                <LockWrapperComponent featureName="lifecycle" bypass>
                  {t("menus.jobsdetail.lifecycle")}
                </LockWrapperComponent>
              ),
              children: <JobLifecycleComponent job={job} statuses={bodyshop.md_ro_statuses} />
            },
            {
              key: "dates",
              id: "job-details-dates",
              icon: <CalendarFilled />,
              label: t("menus.jobsdetail.dates"),
              forceRender: true,
              children: <JobsDetailDatesComponent job={job} />
            },

            {
              key: "documents",
              id: "job-details-documents",
              icon: <FileImageFilled style={{ marginRight: 10 }} />,
              label: <LockWrapperComponent featureName="media">{t("jobs.labels.documents")}</LockWrapperComponent>,
              children: bodyshop.uselocalmediaserver ? (
                <JobsDocumentsLocalGallery job={job} />
              ) : (
                <JobsDocumentsGalleryContainer jobId={job.id} />
              )
            },
            {
              key: "notes",
              id: "job-details-notes",
              icon: <Icon component={FaRegStickyNote} />,
              label: t("jobs.labels.notes"),
              children: <JobNotesContainer jobId={job.id} />
            },
            {
              key: "audit",
              icon: <HistoryOutlined />,
              id: "job-details-audit",
              label: (
                <LockWrapperComponent featureName="audit" bypass>
                  {t("jobs.labels.audit")}
                </LockWrapperComponent>
              ),
              children: <JobAuditTrail jobId={job.id} />
            },
            {
              key: "tasks",
              icon: <FaTasks style={{ paddingTop: 3 }} />,
              id: "job-details-tasks",
              label: (
                <Space orientation="horizontal" align="center">
                  <span>{t("jobs.labels.tasks")}</span>
                  {job.tasks_aggregate.aggregate.count > 0 && (
                    <Badge size="small" count={job.tasks_aggregate.aggregate.count} />
                  )}
                </Space>
              ),
              children: (
                <TaskListContainer
                  relationshipType={"jobid"}
                  relationshipId={job.id}
                  query={{ QUERY_JOB_TASKS_PAGINATED }}
                  titleTranslation="tasks.titles.job_tasks"
                  showRo={false}
                />
              )
            }
          ]}
        />
      </Form>
    </div>
  );
}

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

export const transformJobToForm = (job) => {
  const transformedJob = { ...job };

  transformedJob.parts_tax_rates = Object.keys(transformedJob.parts_tax_rates).reduce((acc, parttype) => {
    acc[parttype] = Object.keys(transformedJob.parts_tax_rates[parttype]).reduce((innerAcc, key) => {
      if (key.includes("tx_in")) {
        innerAcc[key] =
          transformedJob.parts_tax_rates[parttype][key] === "Y" ||
          transformedJob.parts_tax_rates[parttype][key] === true;
      } else {
        innerAcc[key] = transformedJob.parts_tax_rates[parttype][key];
      }
      return innerAcc;
    }, {});
    return acc;
  }, {});

  transformedJob.loss_date = transformedJob.loss_date ? dayjs(transformedJob.loss_date) : null;
  transformedJob.date_estimated = transformedJob.date_estimated ? dayjs(transformedJob.date_estimated) : null;

  return transformedJob;
};
