import React, { useEffect, useMemo, useState } from 'react';
import { IMapState } from 'yandex-maps';

import Pin from '@/components/Map/Pin';
import { useVehicleGPS, useVehicleList } from '@/queries/map';

interface IProps {
  data: any;
  mapRef?: React.RefObject<HTMLDivElement>;
  setStateMap: (state: IMapState) => void;
}

const Vehicle: React.FC<IProps> = ({ data, mapRef, setStateMap }) => {
  const [position, setPosition] = useState<[number, number]>([0, 0]);

  const list = useVehicleList();
  const company = useMemo(() => {
    return list.data?.companys?.find((el) => el.id === data.pid);
  }, [data, list]);

  const gpsData = useVehicleGPS(data.dl[0]?.id);

  useEffect(() => {
    if (!gpsData.data) {
      return;
    }
    const currStatus = gpsData.data.status[0];
    setPosition([+currStatus.mlat, +currStatus.mlng]);
  }, [gpsData.data]);

  return (
    <Pin
      position={position}
      mapRef={mapRef}
      setStateMap={setStateMap}
      description={{
        title: data.nm,
        subtitle: company?.nm || '',
      }}
    />
  );
};

export default Vehicle;
