import { GoogleMap, Marker, Autocomplete, useJsApiLoader } from "@react-google-maps/api";
import { MapPin } from "lucide-react";
import { useState, useCallback, useRef, useEffect } from "react";
import { Form, Spinner } from "react-bootstrap";

// Default center (Indonesia) jika data kosong
const defaultCenter = {
    lat: -6.2088,
    lng: 106.8456
};

// Library yang dibutuhkan (static array agar tidak re-render)
const libraries: ("places")[] = ["places"];

interface LocationPickerProps {
    latitude?: string | number | null;
    longitude?: string | number | null;
    onLocationSelect: (lat: string, lng: string, address?: string, subdistrict?: string, city?: string, province?: string) => void;
    apiKey: string;
    height?: string;
}

export default function LocationPicker({ latitude, longitude, onLocationSelect, apiKey, height = '400px' }: LocationPickerProps) {
    const { isLoaded } = useJsApiLoader({
        id: 'google-map-script',
        googleMapsApiKey: apiKey,
        libraries: libraries,
    });

    const [map, setMap] = useState<google.maps.Map | null>(null);
    const [center, setCenter] = useState(defaultCenter);
    const [markerPos, setMarkerPos] = useState<google.maps.LatLngLiteral | null>(null);

    // Ref untuk Autocomplete
    const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null);

    // Sinkronisasi prop latitude/longitude ke state internal map
    useEffect(() => {
        if (latitude && longitude) {
            const newPos = {
                lat: typeof latitude === 'string' ? parseFloat(latitude) : latitude,
                lng: typeof longitude === 'string' ? parseFloat(longitude) : longitude
            };
            setMarkerPos(newPos);
            setCenter(newPos);
        }
    }, [latitude, longitude]);

    const onLoad = useCallback(function callback(map: google.maps.Map) {
        setMap(map);
    }, []);

    const onUnmount = useCallback(function callback(map: google.maps.Map) {
        setMap(null);
    }, []);

    // Handle saat user klik peta
    const handleMapClick = (e: google.maps.MapMouseEvent) => {
        if (e.latLng) {
            const lat = e.latLng.lat();
            const lng = e.latLng.lng();

            setMarkerPos({ lat, lng });
            // Kirim balik ke parent
            onLocationSelect(lat.toString(), lng.toString());
        }
    };

    // Handle saat user memilih dari search bar
    const onPlaceChanged = () => {
        if (autocompleteRef.current !== null) {
            const place = autocompleteRef.current.getPlace();

            if (place.geometry && place.geometry.location) {
                const lat = place.geometry.location.lat();
                const lng = place.geometry.location.lng();
                const address = place.formatted_address;
                const subdistrict = place.address_components ? place.address_components[3].long_name : '';
                const city = place.address_components ? place.address_components[4].long_name : '';
                const province = place.address_components ? place.address_components[5].long_name : '';

                setCenter({ lat, lng });
                setMarkerPos({ lat, lng });

                // Kirim balik ke parent (termasuk alamat jika ada)
                onLocationSelect(lat.toString(), lng.toString(), address, subdistrict, city, province);
            } else {
                console.log("No details available for input: '" + place.name + "'");
            }
        }
    };

    const onLoadAutocomplete = (autocomplete: google.maps.places.Autocomplete) => {
        autocompleteRef.current = autocomplete;
    };

    if (!isLoaded) return <div className="text-center p-5"><Spinner animation="border" /> Memuat Peta...</div>;

    return (
        <div className="position-relative d-flex flex-column gap-1">
            {/* Search Input */}
            <Autocomplete
                onLoad={onLoadAutocomplete}
                onPlaceChanged={onPlaceChanged}
                className="position-absolute top-0 start-0 z-3 rounded m-2"
            >
                <Form.Control
                    type="text"
                    placeholder="Cari lokasi kantor (Ketik alamat...)"
                    className="mb-0"
                />
            </Autocomplete>

            {/* Map */}
            <GoogleMap
                mapContainerStyle={{
                    width: '100%',
                    height: height,
                    borderRadius: '0.375rem',
                }}
                center={center}
                zoom={15}
                onLoad={onLoad}
                onUnmount={onUnmount}
                onClick={handleMapClick}
                options={{
                    streetViewControl: false,
                    mapTypeControl: false,
                }}
            >
                {markerPos && (
                    <Marker position={markerPos} />
                )}
            </GoogleMap>

            <Form.Text className="text-muted">
                * Cari lokasi atau klik pada peta untuk menandai titik koordinat.
            </Form.Text>

            <Form.Text className="text-muted">
                <div className="d-flex gap-2">
                    <div className="flex-shrink-0">
                        <MapPin size={16} className="mb-1 text-primary" />
                    </div>
                    <div className="flex-grow-1">Latitude: {center.lat}, Longitude: {center.lng}</div>
                </div>
            </Form.Text>
        </div>
    );
}