import React, { useEffect, useRef, useState } from 'react';
import { Loader } from '@googlemaps/js-api-loader';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { MapPin } from 'lucide-react';

// Declare global google type for window
declare global {
  interface Window {
    google: any;
  }
}

interface Offer {
  id: string;
  title: string;
  category: string;
  price: number;
  rating: number;
  images: string[];
  location: {
    lat: number;
    lng: number;
    address: string;
  };
}

interface MapViewProps {
  offers: Offer[];
  onOfferClick: (offer: Offer) => void;
}

const MapView: React.FC<MapViewProps> = ({ offers, onOfferClick }) => {
  const mapRef = useRef<HTMLDivElement>(null);
  const [map, setMap] = useState<any | null>(null);
  const [apiKey, setApiKey] = useState<string>('');
  const [isMapLoaded, setIsMapLoaded] = useState(false);
  const [markers, setMarkers] = useState<any[]>([]);

  const loadMap = async (googleMapsApiKey: string) => {
    if (!mapRef.current || !googleMapsApiKey) return;

    try {
      const loader = new Loader({
        apiKey: googleMapsApiKey,
        version: 'weekly',
        libraries: ['places'],
        id: '__googleMapsScriptIdKaribeo'
      });

      const google = await loader.load();
      const { Map } = google.maps;
      
      const mapInstance = new Map(mapRef.current, {
        center: { lat: 18.4861, lng: -69.9312 }, // Santo Domingo, DR
        zoom: 11,
        styles: [
          {
            featureType: 'poi',
            elementType: 'labels',
            stylers: [{ visibility: 'off' }]
          }
        ]
      });

      setMap(mapInstance);
      setIsMapLoaded(true);

      // Add markers for offers
      const newMarkers = offers.map(offer => {
        const marker = new google.maps.Marker({
          position: { lat: offer.location.lat, lng: offer.location.lng },
          map: mapInstance,
          title: offer.title,
          icon: {
            url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
              <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="20" cy="20" r="18" fill="#fe8303" stroke="white" stroke-width="4"/>
                <text x="20" y="26" text-anchor="middle" fill="white" font-size="12" font-weight="bold">$${offer.price}</text>
              </svg>
            `)}`,
            scaledSize: new google.maps.Size(40, 40),
            anchor: new google.maps.Point(20, 20)
          }
        });

        // Create info window
        const infoWindow = new google.maps.InfoWindow({
          content: `
            <div style="padding: 10px; max-width: 200px;">
              <img src="${offer.images[0]}" alt="${offer.title}" style="width: 100%; height: 100px; object-fit: cover; border-radius: 8px; margin-bottom: 8px;" />
              <h3 style="margin: 0 0 4px 0; font-size: 14px; font-weight: bold;">${offer.title}</h3>
              <p style="margin: 0 0 4px 0; font-size: 12px; color: #666;">${offer.location.address}</p>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span style="font-size: 12px; color: #fe8303;">⭐ ${offer.rating}</span>
                <span style="font-size: 14px; font-weight: bold; color: #fe8303;">$${offer.price}</span>
              </div>
            </div>
          `
        });

        marker.addListener('click', () => {
          // Close other info windows
          markers.forEach(m => m.infoWindow?.close());
          
          infoWindow.open(mapInstance, marker);
          onOfferClick(offer);
        });

        // Store info window reference
        (marker as any).infoWindow = infoWindow;

        return marker;
      });

      setMarkers(newMarkers);

    } catch (error) {
      console.error('Error loading Google Maps:', error);
    }
  };

  useEffect(() => {
    const savedApiKey = localStorage.getItem('googleMapsApiKey');
    if (savedApiKey) {
      setApiKey(savedApiKey);
      loadMap(savedApiKey);
    }
  }, [offers]);

  const handleApiKeySubmit = () => {
    // Ya no se muestra el formulario de API key por seguridad.
  };

  if (!isMapLoaded && !apiKey) {
    return (
      <div className="h-96 bg-gray-100 rounded-lg flex items-center justify-center p-8">
        <div className="text-center max-w-md">
          <MapPin className="w-12 h-12 mx-auto mb-4 text-gray-400" />
          <h3 className="text-lg font-semibold mb-2">Google Maps no disponible</h3>
          <p className="text-gray-600 mb-4 text-sm">
            Configura una Google Maps API key restringida por dominio y autoriza este dominio en Google Cloud Console.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-96 bg-gray-100 rounded-lg overflow-hidden">
      <div ref={mapRef} className="w-full h-full" />
      {!isMapLoaded && apiKey && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
            <p className="text-gray-600">Cargando mapa...</p>
          </div>
        </div>
      )}
    </div>
  );
};

export default MapView;