import Icon, {
  BarsOutlined,
  CalendarFilled,
  DollarCircleOutlined,
  FileImageFilled,
  ToolFilled,
} from "@ant-design/icons";
import { Form, notification, Tabs } from "antd";
import moment from "moment";
import queryString from "query-string";
import React, { lazy, Suspense } from "react";
import { useTranslation } from "react-i18next";
import {
  FaHardHat,
  FaHistory,
  FaRegStickyNote,
  FaShieldAlt,
} from "react-icons/fa";
import { connect } from "react-redux";
import { useHistory, useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import FormFieldsChanged from "../../components/form-fields-changed-alert/form-fields-changed-alert.component";
import { CalculateJob } from "../../components/job-totals-table/job-totals.utility";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import { selectBodyshop } from "../../redux/user/user.selectors";

const JobsLinesContainer = lazy(() =>
  import("../../components/job-detail-lines/job-lines.container")
);

const JobsDetailDatesComponent = lazy(() =>
  import("../../components/jobs-detail-dates/jobs-detail-dates.component")
);
const JobsDetailTotals = lazy(() =>
  import("../../components/jobs-detail-totals/jobs-detail-totals.component")
);
const JobsDetailRates = lazy(() =>
  import("../../components/jobs-detail-rates/jobs-detail-rates.component")
);
const JobsDetailHeader = lazy(() =>
  import("../../components/jobs-detail-header/jobs-detail-header.component")
);
const JobsDetailGeneral = lazy(() =>
  import("../../components/jobs-detail-general/jobs-detail-general.component")
);
const JobsDocumentsGalleryContainer = lazy(() =>
  import(
    "../../components/jobs-documents-gallery/jobs-documents-gallery.container"
  )
);
const JobNotesContainer = lazy(() =>
  import("../../components/jobs-notes/jobs-notes.container")
);
const ScheduleJobModalContainer = lazy(() =>
  import("../../components/schedule-job-modal/schedule-job-modal.container")
);
const JobLineUpsertModalContainer = lazy(() =>
  import(
    "../../components/job-lines-upsert-modal/job-lines-upsert-modal.container"
  )
);
const JobsDetailPliContainer = lazy(() =>
  import("../../components/jobs-detail-pli/jobs-detail-pli.container")
);
const JobsDetailAuditContainer = lazy(() =>
  import("../../components/audit-trail-list/audit-trail-list.container")
);
const JobsDetailLaborContainer = lazy(() =>
  import("../../components/jobs-detail-labor/jobs-detail-labor.container")
);
const JobReconciliationModal = lazy(() =>
  import(
    "../../components/job-reconciliation-modal/job-reconciliation.modal.container"
  )
);

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});

export function JobsDetailPage({
  job,
  mutationUpdateJob,
  mutationConvertJob,
  handleSubmit,
  refetch,
  updateJobStatus,
  bodyshop,
}) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const history = useHistory();

  const search = queryString.parse(useLocation().search);
  const formItemLayout = {
    layout: "vertical",
    // size: "small",
  };

  const handleFinish = async (values) => {
    const newTotals = CalculateJob({ ...job, ...values }, bodyshop.shoprates);

    const result = await mutationUpdateJob({
      variables: {
        jobId: job.id,
        job: {
          ...values,
          clm_total: newTotals.totals.total_repairs.toFormat("0.00"),
          owner_owing: newTotals.custPayable.total.toFormat("0.00"),
          job_totals: JSON.stringify(newTotals),
        },
      },
    });

    if (!!!result.errors) {
      notification["success"]({
        message: t("jobs.successes.savetitle"),
      });
      await refetch();
      form.resetFields();
      form.resetFields();
    }
  };

  return (
    <Suspense
      fallback={<LoadingSpinner message={t("general.labels.loadingapp")} />}
    >
      <ScheduleJobModalContainer />
      <JobReconciliationModal />
      <JobLineUpsertModalContainer />
      <Form
        form={form}
        name="JobDetailForm"
        onFinish={handleFinish}
        {...formItemLayout}
        autoComplete={"off"}
        initialValues={{
          ...job,
          loss_date: job.loss_date ? moment(job.loss_date) : null,
        }}
      >
        <FormFieldsChanged form={form} />

        <JobsDetailHeader
          job={job}
          mutationConvertJob={mutationConvertJob}
          refetch={refetch}
          handleSubmit={handleSubmit}
          updateJobStatus={updateJobStatus}
        />
        <Tabs
          defaultActiveKey={search.tab}
          onChange={(key) => history.push({ search: `?tab=${key}` })}
        >
          <Tabs.TabPane
            tab={
              <span>
                <Icon component={FaShieldAlt} />
                {t("menus.jobsdetail.general")}
              </span>
            }
            key="general"
          >
            <JobsDetailGeneral job={job} form={form} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <BarsOutlined />
                {t("menus.jobsdetail.repairdata")}
              </span>
            }
            key="repairdata"
          >
            <JobsLinesContainer
              jobId={job.id}
              joblines={job.joblines}
              refetch={refetch}
            />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <DollarCircleOutlined />
                {t("menus.jobsdetail.rates")}
              </span>
            }
            key="rates"
          >
            <JobsDetailRates job={job} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <DollarCircleOutlined />
                {t("menus.jobsdetail.totals")}
              </span>
            }
            key="totals"
          >
            <JobsDetailTotals job={job} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <ToolFilled />
                {t("menus.jobsdetail.partssublet")}
              </span>
            }
            key="partssublet"
          >
            <JobsDetailPliContainer job={job} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <Icon component={FaHardHat} />
                {t("menus.jobsdetail.labor")}
              </span>
            }
            key="labor"
          >
            <JobsDetailLaborContainer jobId={job.id} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <CalendarFilled />
                {t("menus.jobsdetail.dates")}
              </span>
            }
            key="dates"
          >
            <JobsDetailDatesComponent job={job} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <FileImageFilled />
                {t("jobs.labels.documents")}
              </span>
            }
            key="documents"
          >
            <JobsDocumentsGalleryContainer jobId={job.id} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <Icon component={FaRegStickyNote} />
                {t("jobs.labels.notes")}
              </span>
            }
            key="notes"
          >
            <JobNotesContainer jobId={job.id} />
          </Tabs.TabPane>

          <Tabs.TabPane
            tab={
              <span>
                <Icon component={FaHistory} />
                {t("jobs.labels.audit")}
              </span>
            }
            key="audit"
          >
            <JobsDetailAuditContainer recordId={job.id} />
          </Tabs.TabPane>
        </Tabs>
      </Form>
    </Suspense>
  );
}
export default connect(mapStateToProps, null)(JobsDetailPage);
