"use client";

import { useEffect, useRef } from "react";
import L from "leaflet";
import "leaflet/dist/leaflet.css";

export interface VenueMapProps {
  latitude?: number;
  longitude?: number;
  venueName?: string;
  fullAddress?: string;
  zoom?: number;
}

export function VenueMap({
  latitude = -37.854,
  longitude = 145.15,
  venueName = "Venue Location",
  fullAddress = "Melbourne VIC",
  zoom = 15,
}: VenueMapProps) {
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<L.Map | null>(null);

  useEffect(() => {
    if (!mapContainerRef.current) return;

    // Clean up existing map instance if any to prevent "Map container is already initialized"
    if (mapInstanceRef.current) {
      mapInstanceRef.current.remove();
      mapInstanceRef.current = null;
    }

    // 1. Initialize Map
    const map = L.map(mapContainerRef.current, {
      center: [latitude, longitude],
      zoom: zoom,
      scrollWheelZoom: false,
      zoomControl: true,
    });

    mapInstanceRef.current = map;

    // 2. Add OpenStreetMap Tile Provider (free, no API key required)
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 19,
      attribution:
        '&copy; <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap</a> contributors',
    }).addTo(map);

    // 3. Custom RooSports Marker Pin
    const customIcon = L.divIcon({
      className: "custom-roosports-pin",
      html: `
        <div style="position: relative; display: flex; flex-direction: column; align-items: center; cursor: pointer; transform: translate(-50%, -100%);">
          <div style="background: #0D1B2A; border: 3px solid #ef7d00; border-radius: 50%; width: 38px; height: 38px; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(13,27,42,0.4);">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
              <circle cx="12" cy="10" r="3"></circle>
            </svg>
          </div>
          <div style="width: 0; height: 0; border-left: 6px solid transparent; border-right: 6px solid transparent; border-top: 8px solid #ef7d00; margin-top: -2px;"></div>
        </div>
      `,
      iconSize: [38, 46],
      iconAnchor: [19, 46],
      popupAnchor: [0, -46],
    });

    const directionsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(
      `${venueName}, ${fullAddress}`,
    )}`;

    // 4. Marker with Popup
    const marker = L.marker([latitude, longitude], { icon: customIcon }).addTo(map);
    marker.bindPopup(`
      <div style="font-family: sans-serif; padding: 4px 2px; min-width: 180px;">
        <h4 style="margin: 0 0 4px 0; font-size: 13px; font-weight: bold; color: #0D131A;">${venueName}</h4>
        <p style="margin: 0 0 8px 0; font-size: 11px; color: #546067; line-height: 1.35;">${fullAddress}</p>
        <a href="${directionsUrl}" target="_blank" rel="noopener noreferrer" style="color: #315f70; font-size: 11px; font-weight: bold; text-decoration: underline;">
          Get Directions &#8599;
        </a>
      </div>
    `);

    // 5. Invalidate Size on Mount & Layout Settlement
    map.invalidateSize();
    const t1 = setTimeout(() => map.invalidateSize(), 100);
    const t2 = setTimeout(() => map.invalidateSize(), 300);
    const t3 = setTimeout(() => map.invalidateSize(), 700);

    return () => {
      clearTimeout(t1);
      clearTimeout(t2);
      clearTimeout(t3);
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
      }
    };
  }, [latitude, longitude, venueName, fullAddress, zoom]);

  return (
    <div className="relative z-0 h-72 min-h-[280px] w-full overflow-hidden rounded-[1.8rem] bg-slate-100">
      <div
        id="roosports-venue-map"
        ref={mapContainerRef}
        className="w-full h-full"
        style={{ width: "100%", height: "288px", minHeight: "280px" }}
      />
    </div>
  );
}

export default VenueMap;
