import React, { useEffect, useRef, useState } from "react";
import { Marker, useMapEvents } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import { Alert, Box, Button, Stack, Typography, Zoom } from "@mui/material";
import dynamic from "next/dynamic";
import MapLoading from "@/core/components/MapLayer/Loading";
import HereIcon from "@/assets/images/examine_marker_active.png";

const MapLayer = dynamic(() => import("@/core/components/MapLayer"), {
    loading: () => <MapLoading />,
    ssr: false,
});

const createCustomIcon = (size, iconUrl, labelText, color) => {
    if (labelText) {
        return L.divIcon({
            className: "custom-marker", // Apply your custom CSS class
            html: `
                  <div style="position: relative; text-align: center; width: 50px;">
                    <div style="background-color: ${color}; color: white; border-radius: 20px; padding: 5px;">
                      <span style="font-family: 'IRANSansFaNum', sans-serif;">${labelText}</span>
                    </div>
                    <div style="width: 5px; height: 20px; background: ${color}; margin: auto;border-bottom-left-radius: 50%; border-bottom-right-radius: 50%;"></div>
                  </div>`,
            iconSize: [50, 50],
            iconAnchor: [25, 50],
        });
    }

    return L.icon({
        iconUrl: iconUrl,
        iconSize: size,
        iconAnchor: [size[0] / 2, size[1]],
        popupAnchor: [0, -size[1]],
    });
};
const MAX_ZOOM_FOR_MARKER = 13;

const MapInteraction = ({ setValue, startLat, startLng }) => {
    const [isMarkerLocked, setIsMarkerLocked] = useState(!!(startLat && startLng)); // وضعیت قفل مارکر
    const [enableSend, setEnableSend] = useState(false);
    const [startIconColor, setStartIconColor] = useState(startLat ? "#1CAC66" : "#003d4f"); // رنگ آیکن شروع
    const [markerPosition, setMarkerPosition] = useState(
        startLat && startLng ? { lat: startLat, lng: startLng } : null
    );
    const markerRef = useRef();

    const map = useMapEvents({
        move(e) {
            setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER);
            if (!isMarkerLocked && markerRef.current) {
                markerRef.current.setLatLng(e.target.getCenter());
            }
        },
        zoom(e) {
            setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER);
            if (!isMarkerLocked && markerRef.current) {
                markerRef.current.setLatLng(e.target.getCenter());
            }
        },
    });

    useEffect(() => {
        if (startLat && startLng) {
            const position = { lat: startLat, lng: startLng };
            map.setView(position, 15);
        }
    }, [startLat, startLng, map]);

    const handleMarkerClick = () => {
        if (!enableSend) return;
        if (!isMarkerLocked) {
            const center = map.getCenter();
            setValue("start_point", { lat: center.lat.toString(), lng: center.lng.toString() });
            setMarkerPosition({ lat: center.lat, lng: center.lng }); // به‌روزرسانی موقعیت مارکر
            setIsMarkerLocked(true);
            setStartIconColor("#1CAC66");
        }
    };

    const handleUnlockMarker = () => {
        setValue("start_point", null); // حذف مقدار قبلی
        setIsMarkerLocked(false); // باز کردن قفل مارکر
        setMarkerPosition(null); // تنظیم مارکر به مرکز نقشه
        setStartIconColor("#003d4f");
    };

    return (
        <>
            <Marker
                position={markerPosition || map.getCenter()} // استفاده از موقعیت
                ref={markerRef}
                icon={createCustomIcon([35, 35], HereIcon.src, "اینجا", startIconColor)}
                eventHandlers={{
                    click: handleMarkerClick,
                }}
            />
            <Stack
                direction={"row"}
                justifyContent={"center"}
                sx={{
                    zIndex: "400",
                    width: "100%",
                    position: "absolute",
                    top: 0,
                    left: 0,
                }}
            >
                <Zoom in={!enableSend}>
                    <Alert sx={{ mt: 1, py: 0.5, px: 2, borderRadius: 2, border: 1 }} icon={false} color={"warning"}>
                        برای ثبت محل فعالیت، لطفاً نقشه را بیشتر زوم کنید.
                    </Alert>
                </Zoom>
            </Stack>
            {isMarkerLocked && (
                <Box
                    sx={{
                        position: "absolute",
                        bottom: 10,
                        left: 10,
                        zIndex: 1000,
                    }}
                >
                    <Button variant="contained" onClick={handleUnlockMarker}>
                        ویرایش
                    </Button>
                </Box>
            )}
        </>
    );
};

const MapInfoOneMarker = ({ setValue, errors, StartPoint = null }) => {
    return (
        <Box>
            <Box sx={{ width: "100%", height: "400px", marginBottom: "16px" }}>
                <MapLayer style={{ border: "1px solid #0009", borderRadius: "4px" }}>
                    <MapInteraction
                        setValue={setValue}
                        startLat={StartPoint ? StartPoint.lat : null}
                        startLng={StartPoint ? StartPoint.lng : null}
                    />
                </MapLayer>
            </Box>
            <Box display="flex" gap={2}>
                {errors.start_point && (
                    <Typography color="error" variant="body2">
                        {errors.start_point.message}
                    </Typography>
                )}
            </Box>
        </Box>
    );
};

export default MapInfoOneMarker;
