import Icon, {
  BarsOutlined,
  CalendarFilled,
  DollarCircleOutlined,
  FileImageFilled,
  ToolFilled,
  CheckSquareFilled,
} from "@ant-design/icons";
import { Form, notification, Tabs } from "antd";
import Axios from "axios";
import Dinero from "dinero.js";
import moment from "moment";
import queryString from "query-string";
import React, { lazy, Suspense, useState } 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 LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import { selectBodyshop } from "../../redux/user/user.selectors";
import JobsDetailChecklists from "../../components/jobs-detail-checklists/jobs-detail-checklists.component";

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,
  handleSubmit,
  refetch,
  bodyshop,
}) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const history = useHistory();
  const [loading, setLoading] = useState(false);
  const search = queryString.parse(useLocation().search);
  const formItemLayout = {
    layout: "vertical",
    // size: "small",
  };

  const handleFinish = async (values) => {
    setLoading(true);
    //const newTotals = CalculateJob({ ...job, ...values }, bodyshop.shoprates);
    const newTotals = (
      await Axios.post("/job/totals", {
        job: { ...job, ...values },
      })
    ).data;

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

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

  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
          form={form}
          job={job}
          refetch={refetch}
          handleSubmit={handleSubmit}
          loading={loading}
        />
        <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
              job={job}
              joblines={job.joblines}
              refetch={refetch}
            />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <DollarCircleOutlined />
                {t("menus.jobsdetail.rates")}
              </span>
            }
            key="rates"
          >
            <JobsDetailRates job={job} form={form} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <DollarCircleOutlined />
                {t("menus.jobsdetail.totals")}
              </span>
            }
            key="totals"
          >
            <JobsDetailTotals job={job} refetch={refetch} />
          </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.TabPane
            tab={
              <span>
                <CheckSquareFilled />
                {t("jobs.labels.checklists")}
              </span>
            }
            key="checklists"
          >
            <JobsDetailChecklists job={job} />
          </Tabs.TabPane>
        </Tabs>
      </Form>
    </Suspense>
  );
}
export default connect(mapStateToProps, null)(JobsDetailPage);
