import { useEffect, useRef, useState } from "react";
import { Modal, Button, Spinner } from "react-bootstrap";
import { MdMyLocation } from "react-icons/md";

interface AbsenMapModalProps {
    open: boolean;
    onClose: () => void;
    onAbsen: (lat: number, lng: number) => void;
    officeLocation?: { lat: number; lng: number; name: string };
}

export default function AbsenMapModal({
    open,
    onClose,
    onAbsen,
    officeLocation,
}: AbsenMapModalProps) {
    const mapRef = useRef<HTMLDivElement | null>(null);
    const markerRef = useRef<google.maps.Marker | null>(null);
    const mapInstance = useRef<google.maps.Map | null>(null);

    // State tambahan untuk loading dan koordinat
    const [isLocating, setIsLocating] = useState(false);
    const [userCoords, setUserCoords] =
        useState<google.maps.LatLngLiteral | null>(null);

    const handleRecenter = () => {
        if (!navigator.geolocation) return;

        setIsLocating(true);
        navigator.geolocation.getCurrentPosition(
            (pos) => {
                const newPos = {
                    lat: pos.coords.latitude,
                    lng: pos.coords.longitude,
                };
                setUserCoords(newPos);

                if (mapInstance.current && markerRef.current) {
                    mapInstance.current.setCenter(newPos);
                    mapInstance.current.setZoom(17); // Kunci di level 17
                    markerRef.current.setPosition(newPos);
                }
                setIsLocating(false);
            },
            (err) => {
                setIsLocating(false);
                console.error(err);
            },
            { enableHighAccuracy: true },
        );
    };

    useEffect(() => {
        if (!open || !mapRef.current) return;

        const officeLat = parseFloat(String(officeLocation?.lat));
        const officeLng = parseFloat(String(officeLocation?.lng));
        const officeName = String(officeLocation?.name || "Kantor");
        const isOfficeValid = !isNaN(officeLat) && !isNaN(officeLng);

        const initialCenter = isOfficeValid
            ? { lat: officeLat, lng: officeLng }
            : { lat: -6.2, lng: 106.81 };

        const map = new google.maps.Map(mapRef.current!, {
            center: initialCenter,
            zoom: 17, // Zoom default saat awal buka
            disableDefaultUI: true,
        });
        mapInstance.current = map;

        setIsLocating(true);

        if (isOfficeValid) {
            new google.maps.Circle({
                strokeColor: "#FF0000",
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: "#FF0000",
                fillOpacity: 0.2,
                map: map,
                center: initialCenter,
                radius: 50,
            });

            new google.maps.Marker({
                position: initialCenter,
                map: map,
                label: officeName,
            });
        }

        navigator.geolocation.getCurrentPosition(
            (pos) => {
                const userPos = {
                    lat: pos.coords.latitude,
                    lng: pos.coords.longitude,
                };
                setUserCoords(userPos);

                markerRef.current = new google.maps.Marker({
                    position: userPos,
                    map: map,
                    draggable: true,
                    title: "Lokasi Anda",
                });
                if (isOfficeValid) {
                    const bounds = new google.maps.LatLngBounds();
                    bounds.extend(userPos);
                    bounds.extend(initialCenter);

                    // 1. FitBounds dulu
                    map.fitBounds(bounds, 80);

                    // 2. TAMBAHKAN INI: Batasi agar tidak terlalu nge-zoom
                    const listener = google.maps.event.addListener(
                        map,
                        "idle",
                        () => {
                            // Jika zoom otomatis lebih besar dari 17, paksa ke 17
                            if (map.getZoom()! > 17) {
                                map.setZoom(17);
                            }
                            // Hapus listener agar tidak mengunci zoom saat user mau zoom manual
                            google.maps.event.removeListener(listener);
                        },
                    );
                } else {
                    map.setCenter(userPos);
                    map.setZoom(17); // Set manual jika tidak ada office bounds
                }
                setIsLocating(false);
            },
            (err) => {
                console.error("Geolocation Error:", err);
                setIsLocating(false);
                // Fallback marker jika GPS gagal
                markerRef.current = new google.maps.Marker({
                    position: initialCenter,
                    map: map,
                    draggable: true,
                });
            },
            { enableHighAccuracy: true, timeout: 15000 },
        );

        return () => {
            mapInstance.current = null;
            markerRef.current = null;
        };
    }, [open]); // Hapus officeLocation dari dependency agar tidak re-render terus menerus

    const handleAbsenClick = () => {
        if (!markerRef.current) return;
        const pos = markerRef.current.getPosition();
        if (!pos) return;
        onAbsen(pos.lat(), pos.lng());
    };

    return (
        <Modal show={open} onHide={onClose} fullscreen>
            <Modal.Header closeButton>
                <Modal.Title>Lokasi Absensi</Modal.Title>
            </Modal.Header>
            <Modal.Body
                className="p-0 position-relative"
                style={{ overflow: "hidden" }}
            >
                <div ref={mapRef} style={{ width: "100%", height: "100%" }} />

                {/* TOMBOL LOKASI SAYA */}
                <Button
                    variant="white"
                    className="shadow-sm border-secondary-subtle"
                    onClick={handleRecenter}
                    disabled={isLocating}
                    style={{
                        position: "absolute",
                        right: "20px",
                        bottom: "110px",
                        zIndex: 1057,
                        borderRadius: "50%",
                        width: "50px",
                        height: "50px",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        backgroundColor: "#fff",
                    }}
                >
                    {isLocating ? (
                        <Spinner
                            animation="border"
                            size="sm"
                            variant="primary"
                        />
                    ) : (
                        <MdMyLocation size={24} color="#4285F4" />
                    )}
                </Button>

                {/* AREA TOMBOL ABSEN */}
                <div
                    style={{
                        position: "absolute",
                        bottom: 0,
                        left: 0,
                        right: 0,
                        padding: "20px",
                        background:
                            "linear-gradient(to top, rgba(255,255,255,1), rgba(255,255,255,0))",
                        zIndex: 1056,
                    }}
                >
                    <Button
                        variant={isLocating ? "secondary" : "success"}
                        size="lg"
                        className="w-100 shadow"
                        onClick={handleAbsenClick}
                        disabled={isLocating || !userCoords}
                    >
                        {isLocating ? (
                            <>
                                <Spinner
                                    animation="grow"
                                    size="sm"
                                    className="me-2"
                                />
                                Mendapatkan Lokasi...
                            </>
                        ) : (
                            "Absen Sekarang"
                        )}
                    </Button>
                </div>
            </Modal.Body>
        </Modal>
    );
}
