import React, { useEffect } from "react";
import VehicleDetailComponent from "./vehicles-detail.page.component";
import { useQuery } from "@apollo/react-hooks";
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";

export default function VehicleDetailContainer({ match }) {
  const { vehId } = match.params;
  const { t } = useTranslation();
  const { loading, data, error, refetch } = useQuery(QUERY_VEHICLE_BY_ID, {
    variables: { id: vehId },
    fetchPolicy: "network-only"
  });

  useEffect(() => {
    document.title = t("titles.vehicledetail", {
      vehicle:
        data && 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}`
          : ""
    });
  }, [t, data]);

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent message={error.message} type="error" />;

  if (data.vehicles_by_pk)
    return (
      <VehicleDetailComponent vehicle={data.vehicles_by_pk} refetch={refetch} />
    );
  else
    return (
      <AlertComponent message={t("vehicles.errors.noaccess")} type="error" />
    );
}
