"use client"

import React from "react"
import { GoogleMap, LoadScript, MarkerF, InfoWindowF } from "@react-google-maps/api"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Star, MapPin, Phone, Mail } from "lucide-react"

interface Facility {
  id: string | number
  name: string
  type: string
  location: string
  distance: string | null
  rating: number
  reviewCount: number
  priceRange?: string
  startingPrice?: number
  image: string
  amenities: string[]
  verified: boolean
  featured: boolean
  coordinates: { lat: number | null; lng: number | null }
}

interface GoogleMapComponentProps {
  facilities: Facility[]
  selectedFacility: string | number | null
  onFacilitySelect: (facilityId: string | number | null) => void
  className?: string
}

// Map container style
const mapContainerStyle = {
  width: '100%',
  height: '100%'
}

// Center the map on the center of the United States for better overview
const center = {
  lat: 39.8283,
  lng: -98.5795
}

// Map options - Updated for newer API
const options = {
  disableDefaultUI: false,
  zoomControl: true,
  streetViewControl: false,
  mapTypeControl: true,
  fullscreenControl: false,
  gestureHandling: 'cooperative',
  mapId: undefined, // Use default map styling
}

function GoogleMapComponent({ 
  facilities, 
  selectedFacility, 
  onFacilitySelect,
  className = ""
}: GoogleMapComponentProps) {
  const [isLoaded, setIsLoaded] = React.useState(false)
  
  // You'll need to add your Google Maps API key here
  const GOOGLE_MAPS_API_KEY = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY

  const onLoad = React.useCallback(() => {
    setIsLoaded(true)
  }, [])

  // If no API key is provided, show an interactive facility map
  if (!GOOGLE_MAPS_API_KEY || GOOGLE_MAPS_API_KEY === "your-google-maps-api-key-here" || GOOGLE_MAPS_API_KEY === "undefined") {
    return (
      <div className={`relative rounded-xl overflow-hidden shadow-xl border border-border bg-gradient-to-br from-blue-50 to-indigo-100 ${className}`}>
        {/* Interactive Facility Map Fallback */}
        <div className="h-full flex flex-col items-center justify-center p-6">
          <div className="text-center mb-6">
            <div className="w-16 h-16 mx-auto mb-4 bg-blue-500 rounded-full flex items-center justify-center">
              <MapPin className="w-8 h-8 text-white" />
            </div>
            <h3 className="text-2xl font-bold text-gray-800 mb-2">Facility Locations</h3>
            <p className="text-lg text-gray-600 mb-6">
              Interactive facility map for Springfield, IL area
            </p>
          </div>
          
          <div className="grid grid-cols-2 gap-4 w-full max-w-3xl">
            {facilities.map((facility) => (
              <div 
                key={facility.id} 
                className={`bg-white rounded-lg shadow-lg border-2 p-4 cursor-pointer transition-all duration-200 ${
                  selectedFacility === facility.id 
                    ? "border-blue-500 bg-blue-50 transform scale-105" 
                    : "border-gray-300 hover:border-blue-400 hover:shadow-xl"
                }`}
                onClick={() => onFacilitySelect(selectedFacility === facility.id ? null : facility.id)}
              >
                <div className="relative h-32 w-full mb-3">
                  <img 
                    src={facility.image} 
                    alt={facility.name}
                    className="w-full h-full object-cover rounded-lg"
                  />
                  {facility.featured && (
                    <span className="absolute top-2 right-2 bg-orange-500 text-white px-2 py-1 rounded-full text-xs font-bold">
                      FEATURED
                    </span>
                  )}
                </div>
                <div className="space-y-2">
                  <h4 className="text-lg font-bold text-slate-900">{facility.name}</h4>
                  <div className="bg-blue-100 px-2 py-1 rounded-lg inline-block">
                    <span className="text-sm font-semibold text-blue-800">{facility.type}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                    <span className="text-sm font-bold">{facility.rating}</span>
                    <span className="text-xs text-slate-600">({facility.reviewCount})</span>
                  </div>
                  <p className="text-sm text-slate-600 flex items-center gap-1">
                    <MapPin className="h-3 w-3" />
                    {facility.distance}
                  </p>
                  <div className="bg-green-100 px-2 py-1 rounded-lg">
                    <p className="text-xs text-green-700 font-medium">Starting at</p>
                    <p className="text-sm font-bold text-green-800">${(facility.startingPrice || 0).toLocaleString()}/month</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
          
          {/* API Key Instructions */}
          <div className="mt-8 bg-white/90 p-4 rounded-lg border text-center max-w-md">
            <p className="text-sm text-gray-600 mb-2">To enable Google Maps integration:</p>
            <code className="text-xs bg-gray-100 p-2 rounded block">
              NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=your_api_key_here
            </code>
          </div>
        </div>
        
        {/* Results Counter */}
        <div className="absolute bottom-4 left-4 bg-white/95 backdrop-blur-sm px-4 py-2 rounded-lg shadow-lg border border-white/20 z-20">
          <p className="font-body text-sm font-semibold text-gray-800">
            <span className="text-primary">{facilities.length}</span> facilities found
          </p>
        </div>
      </div>
    )
  }

  return (
    <div className={`relative rounded-xl overflow-hidden shadow-xl border border-border ${className}`}>
      <LoadScript 
        googleMapsApiKey={GOOGLE_MAPS_API_KEY}
        onLoad={onLoad}
        onError={(error) => {
          console.error('Google Maps failed to load:', error);
        }}
      >
        <GoogleMap
          mapContainerStyle={mapContainerStyle}
          center={center}
          zoom={5}
          options={options}
        >
          {facilities
            .filter(facility => 
              facility.coordinates && 
              facility.coordinates.lat !== null && 
              facility.coordinates.lng !== null &&
              typeof facility.coordinates.lat === 'number' &&
              typeof facility.coordinates.lng === 'number'
            )
            .map((facility) => (
              <React.Fragment key={facility.id}>
                <MarkerF
                  position={{
                    lat: facility.coordinates.lat!,
                    lng: facility.coordinates.lng!
                  }}
                  onClick={() => onFacilitySelect(selectedFacility === facility.id ? null : facility.id)}
                  title={facility.name}
                />
                {selectedFacility === facility.id && (
                  <InfoWindowF
                    position={{
                      lat: facility.coordinates.lat!,
                      lng: facility.coordinates.lng!
                    }}
                    onCloseClick={() => onFacilitySelect(null)}
                  >
                    <div className="p-3 min-w-[280px] max-w-[320px]">
                      <div className="flex items-start gap-3">
                        <img
                          src={facility.image}
                          alt={facility.name}
                          className="w-20 h-16 object-cover rounded-lg"
                          onError={(e) => {
                            e.currentTarget.src = "/placeholder.svg";
                          }}
                        />
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h3 className="font-bold text-gray-900 text-lg">{facility.name}</h3>
                            {facility.featured && (
                              <Badge className="bg-orange-500 text-white text-xs font-bold">Featured</Badge>
                            )}
                          </div>
                          <div className="bg-blue-100 px-2 py-1 rounded-lg inline-block mb-2">
                            <span className="text-sm font-semibold text-blue-800">{facility.type}</span>
                          </div>
                          <div className="flex items-center gap-2 mb-3">
                            <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                            <span className="text-lg font-bold">{facility.rating}</span>
                            <span className="text-sm text-gray-500">({facility.reviewCount} reviews)</span>
                          </div>
                          <p className="text-sm text-gray-600 mb-3 flex items-center gap-2">
                            <MapPin className="h-4 w-4" />
                            {facility.distance || 'Distance unknown'}
                          </p>
                          <div className="flex items-center justify-between mb-3">
                            {facility.startingPrice ? (
                              <div className="bg-green-100 px-3 py-2 rounded-lg">
                                <p className="text-sm text-green-700 font-medium">Starting at</p>
                                <p className="text-xl font-bold text-green-800">${facility.startingPrice.toLocaleString()}/month</p>
                              </div>
                            ) : (
                              <div className="bg-blue-100 px-3 py-2 rounded-lg">
                                <p className="text-sm text-blue-700 font-medium">Contact for</p>
                                <p className="text-xl font-bold text-blue-800">Pricing</p>
                              </div>
                            )}
                          </div>
                          <div className="flex gap-2">
                            <Button size="sm" className="bg-blue-600 hover:bg-blue-700 text-white flex-1">
                              <Phone className="h-4 w-4 mr-1" />
                              Call
                            </Button>
                            <Button size="sm" className="bg-green-600 hover:bg-green-700 text-white flex-1">
                              Details
                            </Button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </InfoWindowF>
                )}
              </React.Fragment>
            ))}
        </GoogleMap>
      </LoadScript>
      
      {/* Results Counter */}
      <div className="absolute bottom-4 left-4 bg-white/95 backdrop-blur-sm px-4 py-2 rounded-lg shadow-lg border border-white/20 z-20">
        <p className="font-body text-sm font-bold text-gray-800">
          <span className="text-blue-600">
            {facilities.filter(f => 
              f.coordinates && 
              f.coordinates.lat !== null && 
              f.coordinates.lng !== null &&
              typeof f.coordinates.lat === 'number' &&
              typeof f.coordinates.lng === 'number'
            ).length}
          </span> facilities mapped
        </p>
      </div>
    </div>
  )
}

export default GoogleMapComponent
