import React, { useState } from "react";
import { createCoordinateObject } from "../../../../../../util/validate";
import { Marker, OverlayView, Polyline } from "@react-google-maps/api";
import clientIcon from "../../../../../../assets/icons/client.png";
import { ClientDetailInfo } from "./ClientDetailInfo";
import axiosInstance from "../../../../../../util/axiosInstance";

export const ShowClientOnMap = ({ clientInfo: clientInformation, cluster }) => {
    const [showDetail, setShowDetail] = useState(false);
    const [clientInfo, setClientInfo] = useState({});
    const { client_latitude, client_longitude } = clientInformation;

    const coordinates = createCoordinateObject(
        client_latitude,
        client_longitude
    );
    if (!coordinates) return null;

    const showDetailHandler = async () => {
        const data = await axiosInstance.get(
            `clients/getClientDetail/${clientInformation.client.id}`
        );
        setClientInfo(data.data);
        setShowDetail(true);
    };

    return (
        <>
            <Marker position={coordinates} icon={clientIcon} />
            <Polyline path={[JSON.parse(cluster.coordinates), coordinates]} />

            {!showDetail && (
                <OverlayView
                    position={coordinates}
                    mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
                    getPixelPositionOffset={() => ({
                        x: -23,
                        y: -73,
                    })}
                >
                    <div
                        className="p-2 text-white bg-dark rounded d-flex align-items-center"
                        onContextMenu={showDetailHandler}
                        style={{ position: "absolute", whiteSpace: "nowrap" }}
                    >
                        <p className="m-0">{clientInformation.client.userid}</p>
                        <span
                            className="border-1"
                            title={
                                clientInformation.status === true
                                    ? "Online"
                                    : "Offline"
                            }
                        >
                            <div
                                className={`ms-1 bg-${
                                    clientInformation.status
                                        ? "success"
                                        : "danger"
                                } px-2 py-2 rounded-circle`}
                            />
                        </span>
                    </div>
                </OverlayView>
            )}

            {showDetail && (
                <ClientDetailInfo
                    setShowDetail={setShowDetail}
                    coordinates={coordinates}
                    clientInfo={clientInfo}
                />
            )}
        </>
    );
};
