"use client"

import { useEffect, useState } from "react"
import { MapContainer, TileLayer, Marker, Popup, LayersControl, GeoJSON } from "react-leaflet"
import MarkerClusterGroup from "react-leaflet-cluster"
import L from "leaflet"
import "leaflet/dist/leaflet.css"
import "react-leaflet-cluster/dist/assets/MarkerCluster.css"
import "react-leaflet-cluster/dist/assets/MarkerCluster.Default.css"
import Link from "next/link"
import { PhotoCarousel } from "@/components/ui/PhotoCarousel"

// Fix for default marker icon in react-leaflet
const DefaultIcon = L.icon({
  iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
  iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
  shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  tooltipAnchor: [16, -28],
  shadowSize: [41, 41]
});
L.Marker.prototype.options.icon = DefaultIcon;

type MapEntry = {
  id: string
  title: string
  subjectName: string
  latitude: number
  longitude: number
  city: string
  county: string
  photos: { url: string }[]
  user?: { name: string | null }
}

export default function MapComponent({ entries }: { entries: MapEntry[] }) {
  const [isMounted, setIsMounted] = useState(false)
  const [geoData, setGeoData] = useState<any>(null)

  useEffect(() => {
    fetch("/rovibe/ro_admin_county.geojson")
      .then(res => res.json())
      .then(data => setGeoData(data))
      .catch(err => console.error("Error loading geojson", err))
      
    setIsMounted(true)
  }, [])

  const onEachFeature = (feature: any, layer: L.Layer) => {
    if (feature.properties?.mnemonic) {
      layer.bindTooltip(feature.properties.mnemonic, {
        permanent: true,
        direction: "center",
        className: "county-label",
        interactive: false
      });
    }
  };

  if (!isMounted) return <div style={{ height: "600px", width: "100%", background: "var(--surface-hover)", display: "flex", alignItems: "center", justifyContent: "center" }}>Se încarcă harta...</div>

  return (
    <div style={{ height: "600px", width: "100%", borderRadius: "var(--radius-lg)", overflow: "hidden", border: "1px solid var(--border-color)", zIndex: 0, position: "relative" }}>
      <style>{`
        .county-label {
          background: transparent;
          border: none;
          box-shadow: none;
          font-weight: 700;
          color: #4b5563;
          font-size: 0.75rem;
          text-shadow: 1px 1px 0 rgba(255,255,255,0.8), -1px -1px 0 rgba(255,255,255,0.8), 1px -1px 0 rgba(255,255,255,0.8), -1px 1px 0 rgba(255,255,255,0.8);
        }
        .leaflet-tooltip.county-label::before {
          display: none;
        }
      `}</style>
      <MapContainer 
        center={[45.9432, 24.9668]} // Centrul României
        zoom={7} 
        style={{ height: "100%", width: "100%" }}
      >
        <LayersControl position="topright">
          <LayersControl.BaseLayer checked name="Harta actuală">
            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
          </LayersControl.BaseLayer>

          <LayersControl.BaseLayer name="Satelit">
            <TileLayer
              attribution='&copy; <a href="https://www.esri.com/">Esri</a>, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
              url="https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
            />
          </LayersControl.BaseLayer>

          <LayersControl.BaseLayer name="Hartă istorică">
            <TileLayer
              attribution='&copy; <a href="https://geo-spatial.org">geo-spatial.org</a>'
              url="https://services.geo-spatial.org/geoserver/gwc/service/wmts?service=WMTS&request=GetTile&version=1.0.0&layer=eharta:mozaic_planuri_tragere_20k&style=&tilematrixset=EPSG:900913&format=image/png&tilematrix=EPSG:900913:{z}&tilerow={y}&tilecol={x}"
            />
          </LayersControl.BaseLayer>
        </LayersControl>
        
        {geoData && (
          <GeoJSON 
            data={geoData} 
            interactive={false}
            style={{
              color: "#4b5563",
              weight: 1.5,
              fillOpacity: 0,
              interactive: false
            }} 
            onEachFeature={onEachFeature}
          />
        )}
        
        <MarkerClusterGroup chunkedLoading>
          {entries.map((entry: any) => (
            <Marker 
              key={entry.id} 
              position={[entry.latitude, entry.longitude]}
            >
              <Popup>
                <div style={{ width: "220px" }}>
                  {entry.photos.length > 0 && (
                    <div style={{ marginBottom: "0.5rem" }}>
                      <PhotoCarousel 
                        photos={entry.photos} 
                        altText={entry.title} 
                        height="120px" 
                        borderRadius="4px" 
                      />
                    </div>
                  )}
                  <h3 style={{ margin: "0 0 0.25rem 0", fontSize: "1rem" }}>{entry.title}</h3>
                  <p style={{ margin: "0 0 0.5rem 0", fontSize: "0.85rem", color: "#666" }}>{entry.city}, {entry.county}</p>
                  {entry.user?.name && (
                    <p style={{ margin: "0 0 0.5rem 0", fontSize: "0.8rem", color: "#888" }}>De: {entry.user.name}</p>
                  )}
                  
                  <Link 
                    href={`/entry/${entry.id}`} 
                    style={{ display: "block", textAlign: "center", background: "var(--primary)", color: "white", padding: "0.4rem", borderRadius: "4px", textDecoration: "none", fontSize: "0.85rem", fontWeight: 500 }}
                  >
                    Vezi detalii
                  </Link>
                </div>
              </Popup>
            </Marker>
          ))}
        </MarkerClusterGroup>
      </MapContainer>
    </div>
  )
}
