import { useEffect } from "react";
import VehicleDetailComponent from "./vehicles-detail.page.component";
import { useQuery } from "@apollo/client/react";
import { useParams } from "react-router-dom";
import { QUERY_VEHICLE_BY_ID } from "../../graphql/vehicles.queries";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import AlertComponent from "../../components/alert/alert.component";
import { useTranslation } from "react-i18next";
import { addRecentItem, setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { connect } from "react-redux";
import { CreateRecentItem } from "../../utils/create-recent-item";
import NotFound from "../../components/not-found/not-found.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { selectIsPartsEntry } from "../../redux/application/application.selectors";
import { createStructuredSelector } from "reselect";
import getPartsBasePath from "../../utils/getPartsBasePath.js";

const mapStateToProps = createStructuredSelector({
  isPartsEntry: selectIsPartsEntry
});

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  addRecentItem: (item) => dispatch(addRecentItem(item)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function VehicleDetailContainer({ setBreadcrumbs, addRecentItem, setSelectedHeader, isPartsEntry }) {
  const { vehId } = useParams();
  const { t } = useTranslation();
  const basePath = getPartsBasePath(isPartsEntry);

  const { loading, data, error, refetch } = useQuery(QUERY_VEHICLE_BY_ID, {
    variables: { id: vehId },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    document.title = t("titles.vehicledetail", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      }),
      vehicle: data?.vehicles_by_pk
        ? `${data.vehicles_by_pk?.v_model_yr || ""} ${
            data.vehicles_by_pk?.v_make_desc || ""
          } ${data.vehicles_by_pk?.v_model_desc || ""}`
        : ""
    });
    setSelectedHeader("vehicles");

    const crumbs = [];
    if (isPartsEntry) crumbs.push({ link: "/parts", label: t("titles.bc.parts") });
    crumbs.push({ link: `${basePath}/vehicles`, label: t("titles.bc.vehicles") });
    crumbs.push({
      link: `${basePath}/vehicles/${vehId}`,
      label: t("titles.bc.vehicle-details", {
        vehicle: data?.vehicles_by_pk
          ? `${data.vehicles_by_pk?.v_model_yr || ""} ${
              data.vehicles_by_pk?.v_make_desc || ""
            } ${data.vehicles_by_pk?.v_model_desc || ""}`
          : ""
      })
    });

    setBreadcrumbs(crumbs);

    if (data?.vehicles_by_pk)
      addRecentItem(
        CreateRecentItem(
          vehId,
          "vehicle",
          `${data.vehicles_by_pk.v_vin || "N/A"} | ${
            data.vehicles_by_pk.v_model_yr || ""
          } ${data.vehicles_by_pk.v_make_desc || ""} ${data.vehicles_by_pk.v_model_desc || ""}`.trim(),
          `${basePath}/vehicles/${vehId}`
        )
      );
  }, [t, data, setBreadcrumbs, vehId, addRecentItem, setSelectedHeader, basePath, isPartsEntry]);

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;
  if (!data.vehicles_by_pk) return <NotFound />;
  return <VehicleDetailComponent vehicle={data.vehicles_by_pk} refetch={refetch} />;
}

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