import { useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

interface GoogleMapsProps {
    address: string;
    businessName?: string;
}

export default function GoogleMaps({ address, businessName }: GoogleMapsProps) {
    const mapRef = useRef<HTMLDivElement>(null);
    const mapInstanceRef = useRef<google.maps.Map | null>(null);

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

        const initializeMap = () => {
            const geocoder = new google.maps.Geocoder();
            
            geocoder.geocode({ address }, (results, status) => {
                if (status === 'OK' && results?.[0]) {
                    const location = results[0].geometry.location;
                    
                    const map = new google.maps.Map(mapRef.current!, {
                        zoom: 15,
                        center: location,
                        mapTypeControl: true,
                        streetViewControl: true,
                        fullscreenControl: true,
                    });

                    new google.maps.Marker({
                        position: location,
                        map: map,
                        title: businessName || 'Ubicación del negocio',
                    });

                    mapInstanceRef.current = map;
                } else {
                    console.error('Geocode was not successful for the following reason: ' + status);
                }
            });
        };

        if (window.google && window.google.maps) {
            initializeMap();
        } else {
            // Load Google Maps API if not already loaded
            const script = document.createElement('script');
            script.src = `https://maps.googleapis.com/maps/api/js?key=${import.meta.env.VITE_GOOGLE_MAPS_API_KEY}&libraries=places`;
            script.async = true;
            script.defer = true;
            script.onload = initializeMap;
            document.head.appendChild(script);
        }
    }, [address, businessName]);

    if (!address) {
        return (
            <Card className="rounded-xl">
                <CardHeader>
                    <CardTitle>Mapa</CardTitle>
                    <CardDescription>
                        No hay dirección disponible para mostrar el mapa.
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <div className="h-96 bg-muted rounded-xl flex items-center justify-center">
                        <p className="text-muted-foreground">Dirección no disponible</p>
                    </div>
                </CardContent>
            </Card>
        );
    }

    return (
        <Card className="rounded-xl">
            <CardHeader>
                <CardTitle>Ubicación</CardTitle>
                <CardDescription>
                    {address}
                </CardDescription>
            </CardHeader>
            <CardContent>
                <div 
                    ref={mapRef} 
                    className="h-96 w-full rounded-xl border"
                    style={{ minHeight: '400px' }}
                />
            </CardContent>
        </Card>
    );
}
