import { useQuery } from "@apollo/client";
import moment from "moment";
import React from "react";
import { QUERY_AVAILABLE_CC } from "../../graphql/courtesy-car.queries";
import AlertComponent from "../alert/alert.component";
import ContractCarsComponent from "./contract-cars.component";

export default function ContractCarsContainer({ selectedCarState, form }) {
  const { loading, error, data } = useQuery(QUERY_AVAILABLE_CC, {
    variables: { today: moment().format("YYYY-MM-DD") },
  });

  const [selectedCar, setSelectedCar] = selectedCarState;

  const handleSelect = (record) => {
    setSelectedCar(record);

    form.setFieldsValue({
      kmstart: record.mileage,
      dailyrate: record.dailycost,
      fuelout: record.fuel,
      damage: record.damage,
    });
  };

  if (error) return <AlertComponent message={error.message} type="error" />;
  return (
    <ContractCarsComponent
      handleSelect={handleSelect}
      selectedCarId={selectedCar && selectedCar.id}
      loading={loading}
      data={data ? data.courtesycars : []}
    />
  );
}
