'use client';

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

// Fix for default markers in react-leaflet
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
});

interface LocationData {
  name: string;
  lat: number;
  lng: number;
  available: boolean;
  passType: string;
}

interface MapComponentProps {
  locations: LocationData[];
}

const createCustomIcon = (available: boolean) => {
  const color = available ? '#4CAF50' : '#f44336';
  
  return L.divIcon({
    className: 'custom-marker',
    html: `<div style="
      background-color: ${color};
      width: 20px;
      height: 20px;
      border-radius: 50%;
      border: 2px solid white;
      box-shadow: 0 2px 4px rgba(0,0,0,0.3);
    "></div>`,
    iconSize: [20, 20],
    iconAnchor: [10, 10],
  });
};

export default function MapComponent({ locations }: MapComponentProps) {
  // Center map on San Diego
  const center: [number, number] = [32.7157, -117.1611];

  return (
    <MapContainer
      center={center}
      zoom={11}
      zoomControl={false}
      style={{ height: '100%', width: '100%' }}
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      
      {locations.map((location, index) => (
        <Marker
          key={`${location.name}-${index}`}
          position={[location.lat, location.lng]}
          icon={createCustomIcon(location.available)}
        >
          <Popup>
            <div>
              <h3 style={{ margin: '0 0 8px 0', fontSize: '16px' }}>
                {location.name} Library
              </h3>
              <p style={{ margin: '4px 0' }}>
                <strong>Status:</strong> {location.available ? 'Available' : 'Not Available'}
              </p>
              <p style={{ margin: '4px 0' }}>
                <strong>Pass Type:</strong> {location.passType}
              </p>
            </div>
          </Popup>
        </Marker>
      ))}
    </MapContainer>
  );
}
