import React, { useEffect, useRef, useState } from 'react';
import { IonContent, IonPage, IonRow, IonCol, useIonViewDidEnter } from '@ionic/react';
import { useHistory } from 'react-router-dom';
import namelogo from '../../assets/namelogo.png';
import back from '../../assets/back.png';
import { useFunctionService } from '../components/Layout';

const mapContainerStyle = {
    width: '100%',
    height: '100vh',
};

const AddAddresses: React.FC = () => {
    const history = useHistory();
    const mapRef = useRef<HTMLDivElement>(null); // Ref for the map container
    const [markerPosition, setMarkerPosition] = useState({ lat: 14.081999, lng: -87.202438 });
    const [direccion, setDireccion] = useState('');
    const mapInstance = useRef<google.maps.Map | null>(null); // Store the map instance
    const markerInstance = useRef<google.maps.Marker | null>(null); // Store the marker instance
    const [resi, setResi] = useState('');
    const { showToast } = useFunctionService();
    const backtomyaddress = () => {
        history.push('/myaddress');
    }

    useIonViewDidEnter(() => {
        showToast("Arrastra el marcador para ubicar tu dirección que deseas guardar");
    });

    useEffect(() => {

        if (!mapRef.current) return;

        // Initialize Google Map only once
        if (!mapInstance.current) {
            // Initialize the map
            mapInstance.current = new google.maps.Map(mapRef.current, {
                center: markerPosition,
                zoom: 15,
                streetViewControl: false, // Disable Street View control
                mapTypeControl: false, // Disable Map/Satellite switch
                fullscreenControl: false, // Disable fullscreen button
                   styles: [
                                {
                                    "featureType": "all",
                                    "elementType": "geometry",
                                    "stylers": [{ "color": "#03081a" }]
                                },
                                {
                                    "featureType": "all",
                                    "elementType": "labels.text.fill",
                                    "stylers": [{ "color": "#8899cc" }, { "weight": "1.2" }]
                                },
                                {
                                    "featureType": "all",
                                    "elementType": "labels.text.stroke",
                                    "stylers": [{ "color": "#03081a" }, { "weight": "2" }]
                                },
                                {
                                    "featureType": "all",
                                    "elementType": "labels.icon",
                                    "stylers": [{ "visibility": "off" }]
                                },
                                {
                                    "featureType": "landscape",
                                    "elementType": "geometry",
                                    "stylers": [{ "color": "#060d22" }]
                                },
                                {
                                    "featureType": "landscape.natural",
                                    "elementType": "geometry",
                                    "stylers": [{ "color": "#04091e" }]
                                },
                                {
                                    "featureType": "poi",
                                    "elementType": "geometry",
                                    "stylers": [{ "color": "#060d22" }]
                                },
                                {
                                    "featureType": "poi.park",
                                    "elementType": "geometry",
                                    "stylers": [{ "color": "#051428" }]
                                },
                                {
                                    "featureType": "poi.park",
                                    "elementType": "labels.text.fill",
                                    "stylers": [{ "color": "#455178" }]
                                },
                                {
                                    "featureType": "road",
                                    "elementType": "geometry.fill",
                                    "stylers": [{ "color": "#062F81" }]
                                },
                                {
                                    "featureType": "road",
                                    "elementType": "geometry.stroke",
                                    "stylers": [{ "color": "#0a3fa8" }, { "weight": "0.5" }]
                                },
                                {
                                    "featureType": "road.highway",
                                    "elementType": "geometry.fill",
                                    "stylers": [{ "color": "#0a3fa8" }]
                                },
                                {
                                    "featureType": "road.highway",
                                    "elementType": "geometry.stroke",
                                    "stylers": [{ "color": "#1a5cff" }, { "weight": "0.8" }]
                                },
                                {
                                    "featureType": "road.arterial",
                                    "elementType": "geometry.fill",
                                    "stylers": [{ "color": "#062F81" }]
                                },
                                {
                                    "featureType": "road.local",
                                    "elementType": "geometry.fill",
                                    "stylers": [{ "color": "#051f5a" }]
                                },
                                {
                                    "featureType": "transit",
                                    "elementType": "geometry",
                                    "stylers": [{ "color": "#04091e" }]
                                },
                                {
                                    "featureType": "water",
                                    "elementType": "geometry",
                                    "stylers": [{ "color": "#020510" }]
                                },
                                {
                                    "featureType": "water",
                                    "elementType": "labels.text.fill",
                                    "stylers": [{ "color": "#455178" }]
                                }
                                ],
                disableDefaultUI: true,
            });

            // Initialize the marker
            markerInstance.current = new google.maps.Marker({
                position: markerPosition,
                map: mapInstance.current,
                draggable: true,
            });

            // Add drag event listener
            markerInstance.current.addListener('dragend', (e) => {
                const lat = e.latLng.lat();
                const lng = e.latLng.lng();
                setMarkerPosition({ lat, lng });
            });
        } else if (markerInstance.current) {
            // Update marker's position without creating a new one
            markerInstance.current.setPosition(markerPosition);
        }
    }, [markerPosition]); // Dependency on markerPosition

    const guardarDireccion = () => {
        //validations
        if (!direccion) {
            alert('Por favor ingrese un nombre para la dirección');
            return;
        }
        if (!resi) {
            alert('Por favor ingrese un nombre para la residencial');
            return;
        }


        // Retrieve current addresses from localStorage
        const savedAddresses = JSON.parse(localStorage.getItem('savedAddress')) || [];

        // Ensure it's an array
        const addressesArray = Array.isArray(savedAddresses) ? savedAddresses : [savedAddresses];

        // Create the new address object
        const newAddress = {
            direccion,
            resi,
            lat: markerPosition.lat,
            lng: markerPosition.lng,
        };

        // Push the new address to the array
        addressesArray.push(newAddress);

        // Save the updated array back to localStorage
        localStorage.setItem('savedAddress', JSON.stringify(addressesArray));

        alert('Dirección guardada con éxito!');
        history.push('/myaddress');
    };

    return (
        <IonPage>
            <IonContent>
                <div className="relative">

                    <div className="absolute page3">
                        <div className="headerpositioningspacer"></div>
                        <IonRow>
                            <IonCol size="6"></IonCol>
                            <IonCol size="3">
                                <img className="logoname" src={namelogo} alt="Name Logo" />
                            </IonCol>
                            <IonCol size="3">
                                <img className="logoposhome" onClick={backtomyaddress} src={back} alt="Back" />
                            </IonCol>
                        </IonRow>
                    </div>

                    {/* Address input and save button */}
                    <div className="abosolutecard mt-1 page3">
                        <p className="lbl">Nombre de la dirección</p>
                        <input
                            type="text"
                            placeholder="Mi Casa"
                            className="input1 mb-1"
                            value={direccion}
                            onChange={(e) => setDireccion(e.target.value)}
                        />
                        <input
                            type="text"
                            placeholder="Nombre de la Colonia/Residencial"
                            className="input1 mb-1"
                            value={resi}
                            onChange={(e) => setResi(e.target.value)}
                        />
                        <div className="btn1 mt-3" onClick={guardarDireccion}>
                            <p>GUARDAR</p>
                        </div>
                    </div>

                    {/* Map container */}
                    <div id="map" ref={mapRef} className="absolute page1" style={mapContainerStyle}></div>

                </div>

            </IonContent>
        </IonPage>
    );
};

export default AddAddresses;
