import { useQuery } from "@apollo/client/react";
import dayjs from "../../utils/day";
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: dayjs().format("YYYY-MM-DD") },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  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 title={error.message} type="error" />;
  return (
    <ContractCarsComponent
      handleSelect={handleSelect}
      selectedCarId={selectedCar && selectedCar.id}
      loading={loading}
      data={data ? data.courtesycars : []}
    />
  );
}
