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, FaInfo, FaRegStickyNote, FaShieldAlt } from "react-icons/fa";
import { connect } from "react-redux";
import { useHistory, useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
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 JobsDetailClaims = lazy(() =>
  import("../../components/jobs-detail-claims/jobs-detail-claims.component")
);
const JobsDetailDatesComponent = lazy(() =>
  import("../../components/jobs-detail-dates/jobs-detail-dates.component")
);
const JobsDetailFinancials = lazy(() =>
  import(
    "../../components/jobs-detail-financial/jobs-detail-financial.component"
  )
);
const JobsDetailHeader = lazy(() =>
  import("../../components/jobs-detail-header/jobs-detail-header.component")
);
const JobsDetailInsurance = lazy(() =>
  import(
    "../../components/jobs-detail-insurance/jobs-detail-insurance.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 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 = {
    labelCol: {
      xs: { span: 12 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
    },
  };

  const handleFinish = (values) => {
    const newTotals = CalculateJob({ ...job, ...values }, bodyshop.shoprates);
    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),
        },
      },
    }).then((r) => {
      notification["success"]({
        message: t("jobs.successes.savetitle"),
      });
      refetch().then((r) => form.resetFields());
    });
  };

  return (
    <Suspense
      fallback={<LoadingSpinner message={t("general.labels.loadingapp")} />}>
      <ScheduleJobModalContainer />
      <JobLineUpsertModalContainer />
      <Form
        form={form}
        //onFieldsChange={(a, b) => console.log("a,b", a, b)}
        name='JobDetailForm'
        onFinish={handleFinish}
        {...formItemLayout}
        autoComplete={"off"}
        initialValues={{
          ...job,
          loss_date: job.loss_date ? moment(job.loss_date) : null,
          date_estimated: job.date_estimated
            ? moment(job.date_estimated)
            : null,
          date_open: job.date_open ? moment(job.date_open) : null,
          date_scheduled: job.date_scheduled
            ? moment(job.date_scheduled)
            : null,
          scheduled_in: job.scheduled_in ? moment(job.scheduled_in) : null,
          actual_in: job.actual_in ? moment(job.actual_in) : null,
          scheduled_completion: job.scheduled_completion
            ? moment(job.scheduled_completion)
            : null,
          actual_completion: job.actual_completion
            ? moment(job.actual_completion)
            : null,
          scheduled_delivery: job.scheduled_delivery
            ? moment(job.scheduled_delivery)
            : null,
          actual_delivery: job.actual_delivery
            ? moment(job.actual_delivery)
            : null,
          date_invoiced: job.date_invoiced ? moment(job.date_invoiced) : null,
          date_closed: job.date_closed ? moment(job.date_closed) : null,
          date_exported: job.date_exported ? moment(job.date_exported) : null,
        }}>
        <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={FaInfo} />
                {t("menus.jobsdetail.claimdetail")}
              </span>
            }
            key='claimdetail'>
            <JobsDetailClaims job={job} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <Icon component={FaShieldAlt} />
                {t("menus.jobsdetail.insurance")}
              </span>
            }
            key='insurance'>
            <JobsDetailInsurance job={job} form={form} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <BarsOutlined />
                {t("menus.jobsdetail.repairdata")}
              </span>
            }
            key='repairdata'>
            <JobsLinesContainer jobId={job.id} />
          </Tabs.TabPane>
          <Tabs.TabPane
            tab={
              <span>
                <DollarCircleOutlined />
                {t("menus.jobsdetail.financials")}
              </span>
            }
            key='financials'>
            <JobsDetailFinancials 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);
