import { useMutation, useQuery } from "@apollo/client/react";
import { Button, Card, Col, Form, Input, Modal, Result, Row, Select, Space, Switch, Typography } from "antd";
import { useEffect, useState, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useParams } from "react-router-dom";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { some } from "lodash";
import axios from "axios";
import AlertComponent from "../../components/alert/alert.component";
import JobCalculateTotals from "../../components/job-calculate-totals/job-calculate-totals.component";
import ScoreboardAddButton from "../../components/job-scoreboard-add-button/job-scoreboard-add-button.component";
import JobsAdminStatus from "../../components/jobs-admin-change-status/jobs-admin-change.status.component";
import JobsAdminClass from "../../components/jobs-admin-class/jobs-admin-class.component";
import JobsAdminDatesChange from "../../components/jobs-admin-dates/jobs-admin-dates.component";
import JobsAdminDeleteIntake from "../../components/jobs-admin-delete-intake/jobs-admin-delete-intake.component";
import JobsAdminMarkReexport from "../../components/jobs-admin-mark-reexport/jobs-admin-mark-reexport.component";
import JobAdminOwnerReassociate from "../../components/jobs-admin-owner-reassociate/jobs-admin-owner-reassociate.component";
import JobsAdminUnvoid from "../../components/jobs-admin-unvoid/jobs-admin-unvoid.component";
import JobAdminVehicleReassociate from "../../components/jobs-admin-vehicle-reassociate/jobs-admin-vehicle-reassociate.component";
import JobsAdminRemoveAR from "../../components/jobs-admin-remove-ar/jobs-admin-remove-ar.component";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import NotFound from "../../components/not-found/not-found.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import RREarlyROModal from "../../components/dms-post-form/rr-early-ro-modal";
import { GET_JOB_BY_PK, CONVERT_JOB_TO_RO } from "../../graphql/jobs.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { createStructuredSelector } from "reselect";
import { useSocket } from "../../contexts/SocketIO/useSocket";
import { useNotification } from "../../contexts/Notifications/notificationContext";
import { DMS_MAP, getDmsMode } from "../../utils/dmsUtils";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import AuditTrailMapping from "../../utils/AuditTrailMappings";

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

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key)),
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});

const colSpan = {
  sm: { span: 24 },
  md: { span: 12 },
  lg: { span: 8 },
  xl: { span: 6 }
};

const cardStyle = {
  height: "100%"
};

export function JobsCloseContainer({ setBreadcrumbs, setSelectedHeader, bodyshop, insertAuditTrail }) {
  const { jobId } = useParams();
  const { loading, error, data, refetch } = useQuery(GET_JOB_BY_PK, {
    variables: { id: jobId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });
  const { t } = useTranslation();
  const { socket } = useSocket(); // Extract socket from context
  const notification = useNotification();
  const [showEarlyROModal, setShowEarlyROModal] = useState(false);
  const [showConvertModal, setShowConvertModal] = useState(false);
  const [convertLoading, setConvertLoading] = useState(false);
  const [form] = Form.useForm();
  const [mutationConvertJob] = useMutation(CONVERT_JOB_TO_RO);
  const allFormValues = Form.useWatch([], form);

  // Get Fortellis treatment for proper DMS mode detection
  const {
    treatments: { Fortellis }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Fortellis"],
    splitKey: bodyshop?.imexshopid
  });

  // Check if bodyshop has Reynolds integration using the proper getDmsMode function
  const dmsMode = getDmsMode(bodyshop, Fortellis.treatment);
  const isReynoldsMode = dmsMode === DMS_MAP.reynolds;
  const job = data?.jobs_by_pk;
  useEffect(() => {
    setSelectedHeader("activejobs");
    document.title = t("titles.jobs-admin", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      }),
      ro_number: data ? data.jobs_by_pk && data.jobs_by_pk.ro_number : null
    });

    setBreadcrumbs([
      {
        link: `/manage/jobs/`,
        label: t("titles.bc.jobs")
      },
      {
        link: `/manage/jobs/${jobId}/`,
        label: t("titles.bc.jobs-detail", {
          number: data ? data.jobs_by_pk && data.jobs_by_pk.ro_number : null
        })
      },
      {
        link: `/manage/jobs/${jobId}/admin`,
        label: t("titles.bc.jobs-admin")
      }
    ]);
  }, [setBreadcrumbs, t, jobId, data, setSelectedHeader]);

  const handleEarlyROSuccess = (result) => {
    notification.success({
      title: t("jobs.successes.early_ro_created"),
      description: `RO Number: ${result.roNumber || "N/A"}`
    });
    setShowEarlyROModal(false);
    refetch?.();
  };

  const handleConvert = async ({ employee_csr, category, ...values }) => {
    if (!job?.id) return;
    setConvertLoading(true);
    const res = await mutationConvertJob({
      variables: {
        jobId: job.id,
        job: {
          converted: true,
          ...(bodyshop?.enforce_conversion_csr ? { employee_csr } : {}),
          ...(bodyshop?.enforce_conversion_category ? { category } : {}),
          ...values
        }
      }
    });

    if (values.ca_gst_registrant) {
      await axios.post("/job/totalsssu", {
        id: job.id
      });
    }

    if (!res.errors) {
      refetch();
      notification.success({
        title: t("jobs.successes.converted")
      });

      insertAuditTrail({
        jobid: job.id,
        operation: AuditTrailMapping.jobconverted(res.data.update_jobs.returning[0].ro_number),
        type: "jobconverted"
      });

      setShowConvertModal(false);
    }
    setConvertLoading(false);
  };

  const submitDisabled = useCallback(() => some(allFormValues, (v) => v === undefined), [allFormValues]);

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;
  if (!data.jobs_by_pk) return <NotFound />;
  if (!data.jobs_by_pk.job_totals)
    return <Result title={t("jobs.errors.nofinancial")} extra={<JobCalculateTotals job={data.jobs_by_pk} />} />;

  return (
    <RbacWrapper action="jobs:admin">
      <Typography.Title level={4} style={{ color: "tomato" }}>
        {t("jobs.labels.adminwarning")}
      </Typography.Title>
      <Row gutter={[16, 16]}>
        <Col {...colSpan}>
          <Card style={cardStyle}>
            <Space wrap>
              <ScoreboardAddButton
                job={data ? data.jobs_by_pk : {}}
                disabled={(data && data.jobs_by_pk.voided) || (data.jobs_by_pk && !data.jobs_by_pk.converted)}
              />
              <JobsAdminDeleteIntake job={data ? data.jobs_by_pk : {}} />
              <JobsAdminMarkReexport job={data ? data.jobs_by_pk : {}} />
              <JobsAdminUnvoid job={data ? data.jobs_by_pk : {}} />
              <JobsAdminStatus job={data ? data.jobs_by_pk : {}} />
              <JobsAdminRemoveAR job={data ? data.jobs_by_pk : {}} />
              {isReynoldsMode && job?.converted && !job?.dms_id && !job?.dms_customer_id && !job?.dms_advisor_id && (
                <Button className="ant-btn ant-btn-default" onClick={() => setShowEarlyROModal(true)}>
                  {t("jobs.actions.dms.createearlyro", "Create RR RO")}
                </Button>
              )}
              {isReynoldsMode && !job?.converted && !job?.dms_id && (
                <Button type="primary" danger onClick={() => setShowConvertModal(true)}>
                  {t("jobs.actions.convertwithoutearlyro", "Convert without Early RO")}
                </Button>
              )}
            </Space>
          </Card>
        </Col>
        <Col {...colSpan}>
          <Card style={cardStyle}>
            <JobsAdminClass job={data ? data.jobs_by_pk : {}} />
          </Card>
        </Col>
        <Col {...colSpan}>
          <Card style={cardStyle}>
            <JobAdminOwnerReassociate job={data ? data.jobs_by_pk : {}} />
          </Card>
        </Col>
        <Col {...colSpan}>
          <Card style={cardStyle}>
            <JobAdminVehicleReassociate job={data ? data.jobs_by_pk : {}} />
          </Card>
        </Col>

        <Col span={24}>
          <Card style={cardStyle}>
            <JobsAdminDatesChange job={data ? data.jobs_by_pk : {}} />
          </Card>
        </Col>
      </Row>

      {/* Early RO Modal */}
      <RREarlyROModal
        open={showEarlyROModal}
        onClose={() => setShowEarlyROModal(false)}
        onSuccess={handleEarlyROSuccess}
        bodyshop={bodyshop}
        socket={socket}
        job={job}
      />

      {/* Convert without Early RO Modal */}
      <Modal
        open={showConvertModal}
        onCancel={() => setShowConvertModal(false)}
        title={t("jobs.actions.convertwithoutearlyro", "Convert without Early RO")}
        footer={null}
        width={700}
        destroyOnHidden
      >
        <Form
          layout="vertical"
          form={form}
          onFinish={handleConvert}
          initialValues={{
            driveable: true,
            towin: job?.towin,
            ca_gst_registrant: job?.ca_gst_registrant,
            employee_csr: job?.employee_csr,
            category: job?.category,
            referral_source: job?.referral_source,
            referral_source_extra: job?.referral_source_extra ?? ""
          }}
        >
          <Form.Item
            name={["ins_co_nm"]}
            label={t("jobs.fields.ins_co_nm")}
            rules={[
              {
                required: true
              }
            ]}
          >
            <Select showSearch>
              {bodyshop?.md_ins_cos?.map((s, i) => (
                <Select.Option key={i} value={s.name}>
                  {s.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          {bodyshop?.enforce_class && (
            <Form.Item
              name={"class"}
              label={t("jobs.fields.class")}
              rules={[
                {
                  required: bodyshop.enforce_class
                }
              ]}
            >
              <Select>
                {bodyshop?.md_classes?.map((s) => (
                  <Select.Option key={s} value={s}>
                    {s}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          )}
          {bodyshop?.enforce_referral && (
            <>
              <Form.Item
                name={"referral_source"}
                label={t("jobs.fields.referralsource")}
                rules={[
                  {
                    required: bodyshop.enforce_referral
                  }
                ]}
              >
                <Select>
                  {bodyshop?.md_referral_sources?.map((s) => (
                    <Select.Option key={s} value={s}>
                      {s}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item label={t("jobs.fields.referral_source_extra")} name="referral_source_extra">
                <Input />
              </Form.Item>
            </>
          )}
          {bodyshop?.enforce_conversion_csr && (
            <Form.Item
              name={"employee_csr"}
              label={t(
                InstanceRenderManager({
                  imex: "jobs.fields.employee_csr",
                  rome: "jobs.fields.employee_csr_writer"
                })
              )}
              rules={[
                {
                  required: bodyshop.enforce_conversion_csr
                }
              ]}
            >
              <Select
                showSearch={{
                  optionFilterProp: "children",
                  filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }}
                style={{ width: 200 }}
              >
                {bodyshop?.employees
                  ?.filter((emp) => emp.active)
                  ?.map((emp) => (
                    <Select.Option value={emp.id} key={emp.id} name={`${emp.first_name} ${emp.last_name}`}>
                      {`${emp.first_name} ${emp.last_name}`}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
          )}
          {bodyshop?.enforce_conversion_category && (
            <Form.Item
              name={"category"}
              label={t("jobs.fields.category")}
              rules={[
                {
                  required: bodyshop.enforce_conversion_category
                }
              ]}
            >
              <Select allowClear>
                {bodyshop?.md_categories?.map((s) => (
                  <Select.Option key={s} value={s}>
                    {s}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          )}
          {bodyshop?.region_config?.toLowerCase().startsWith("ca") && (
            <Form.Item label={t("jobs.fields.ca_gst_registrant")} name="ca_gst_registrant" valuePropName="checked">
              <Switch />
            </Form.Item>
          )}
          <Form.Item label={t("jobs.fields.driveable")} name="driveable" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label={t("jobs.fields.towin")} name="towin" valuePropName="checked">
            <Switch />
          </Form.Item>

          <Space wrap style={{ marginTop: 16 }}>
            <Button disabled={submitDisabled()} type="primary" danger onClick={() => form.submit()} loading={convertLoading}>
              {t("jobs.actions.convert")}
            </Button>
            <Button onClick={() => setShowConvertModal(false)}>{t("general.actions.close")}</Button>
          </Space>
        </Form>
      </Modal>
    </RbacWrapper>
  );
}

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