import { InfoWindow, Marker, OverlayView } from "@react-google-maps/api";
import { useState } from "react";
import useEditablePolyline from "../../../../hooks/useEditablePolyline";

import clusterIcon from "../../../../assets/icons/cluster.png";
import boxIcon from "../../../../assets/icons/box.png";
import { Button } from "react-bootstrap";
import ShowClientsOnMap from "./ClusterView/ShowClientsOnMap/ShowClientsOnMap";
import { useDispatch } from "react-redux";
import { fetchClusterData } from "../../../../store/asyncMethods/currentClusterMethod";
import { setOpenClusterView } from "../../../../store/reducers/currentClusterReducer";

const Cluster = ({ cluster }) => {
    const dispatch = useDispatch();
    const { setParent } = useEditablePolyline();

    const [showInfoWindow, setShowInfoWindow] = useState(false);

    const onDblClickHandler = (event) => {
        setParent(cluster, event.latLng);
    };

    const onOpenHandler = () => {
        dispatch(setOpenClusterView(true));
        setShowInfoWindow(false);
        dispatch(fetchClusterData(cluster.id));
    };

    return (
        <>
            <Marker
                position={JSON.parse(cluster.coordinates)}
                onDblClick={onDblClickHandler}
                icon={cluster.isBox ? boxIcon : clusterIcon}
                onContextMenu={() => setShowInfoWindow(true)}
            />
            <ShowClientsOnMap cluster={cluster} />
            {showInfoWindow && (
                <InfoWindow
                    position={JSON.parse(cluster.coordinates)}
                    onCloseClick={() => setShowInfoWindow(false)}
                >
                    <>
                        <p className="mb-1 fw-bold h6">{cluster.name}</p>
                        <hr className="my-1" />
                        <div className="d-grid gap-2">
                            <Button
                                size="sm"
                                variant="dark"
                                onClick={onOpenHandler}
                            >
                                Open View
                            </Button>
                        </div>
                    </>
                </InfoWindow>
            )}
            <OverlayView
                position={JSON.parse(cluster.coordinates)}
                mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
                getPixelPositionOffset={() => ({
                    x: -23,
                    y: -73,
                })}
            >
                <div
                    className="p-2 text-white bg-dark rounded"
                    style={{ position: "absolute", whiteSpace: "nowrap" }}
                    onContextMenu={() => setShowInfoWindow(true)}
                >
                    <p className="m-0">{cluster.name}</p>
                </div>
            </OverlayView>
        </>
    );
};

export default Cluster;
