"use client"

import { useEffect, useState, useTransition } from "react"
import { MapContainer, TileLayer, Marker, Popup, LayersControl } from "react-leaflet"
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"
import MarkerClusterGroup from "react-leaflet-cluster"
import { updateEntryStatus } from "@/app/admin/actions"

// Custom marker icons using DivIcon for status-based colors
const createStatusIcon = (status: string) => {
  let color = "var(--warning)" // Default for SUBMITTED
  if (status === "APPROVED") color = "var(--success)"
  if (status === "REJECTED") color = "var(--danger)"

  return L.divIcon({
    className: "custom-status-marker",
    html: `<div style="
      width: 24px;
      height: 24px;
      background-color: ${color};
      border: 3px solid white;
      border-radius: 50%;
      box-shadow: 0 2px 8px rgba(0,0,0,0.3);
      display: flex;
      align-items: center;
      justify-content: center;
    ">
      <div style="width: 6px; height: 6px; background-color: white; border-radius: 50%;"></div>
    </div>`,
    iconSize: [24, 24],
    iconAnchor: [12, 12],
    popupAnchor: [0, -12],
  })
}

type MapEntry = {
  id: string
  title: string
  subjectName: string
  latitude: number
  longitude: number
  city: string
  county: string
  status: "SUBMITTED" | "APPROVED" | "REJECTED"
  userId: string
  photos: { url: string }[]
  user: { name: string | null; class: string | null }
}

type Props = {
  entries: MapEntry[]
  userRole: "ADMIN" | "STUDENT"
  currentUserId: string
}

const filterButtonStyle = {
  padding: "0.4rem 0.8rem",
  borderRadius: "var(--radius-sm)",
  fontSize: "0.8rem",
  fontWeight: 600,
  cursor: "pointer",
  border: "1px solid var(--border-color)",
  transition: "all 0.2s ease"
}

export default function DashboardMap({ entries, userRole, currentUserId }: Props) {
  const [isMounted, setIsMounted] = useState(false)
  const [isPending, startTransition] = useTransition()
  const [filter, setFilter] = useState("ALL") // ALL, SUBMITTED, APPROVED, REJECTED, MINE
  const [activeBaseLayer, setActiveBaseLayer] = useState("OSM") // OSM, SATELLITE, HISTORIC

  useEffect(() => {
    setIsMounted(true)
  }, [])

  const handleStatusChange = async (entryId: string, newStatus: "APPROVED" | "REJECTED" | "SUBMITTED") => {
    startTransition(async () => {
      try {
        await updateEntryStatus(entryId, newStatus)
      } catch (err) {
        alert("Eroare la actualizarea statusului: " + (err instanceof Error ? err.message : "Eroare necunoscută"))
      }
    })
  }

  const filteredEntries = entries.filter((entry) => {
    if (filter === "ALL") return true
    if (filter === "MINE") return entry.userId === currentUserId
    return entry.status === filter
  })

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

  return (
    <div style={{ height: "700px", width: "100%", borderRadius: "var(--radius-lg)", overflow: "hidden", border: "1px solid var(--border-color)", zIndex: 0, position: "relative" }}>
      {/* Filtering UI */}
      <div style={{ 
        position: "absolute", 
        top: "1rem", 
        right: "1rem", 
        zIndex: 1000, 
        background: "var(--surface-color)", 
        padding: "0.5rem", 
        borderRadius: "var(--radius-md)", 
        boxShadow: "var(--shadow-md)",
        border: "1px solid var(--border-color)",
        display: "flex",
        gap: "0.5rem",
        flexWrap: "wrap",
        maxWidth: "calc(100% - 2rem)",
        justifyContent: "flex-end"
      }}>
        {userRole === "ADMIN" ? (
          <>
            <button onClick={() => setFilter("ALL")} style={{ ...filterButtonStyle, background: filter === "ALL" ? "var(--primary)" : "var(--surface-hover)", color: filter === "ALL" ? "white" : "var(--text-main)" }}>Toate</button>
            <button onClick={() => setFilter("SUBMITTED")} style={{ ...filterButtonStyle, background: filter === "SUBMITTED" ? "var(--warning)" : "var(--surface-hover)", color: filter === "SUBMITTED" ? "white" : "var(--text-main)" }}>În așteptare</button>
            <button onClick={() => setFilter("APPROVED")} style={{ ...filterButtonStyle, background: filter === "APPROVED" ? "var(--success)" : "var(--surface-hover)", color: filter === "APPROVED" ? "white" : "var(--text-main)" }}>Aprobate</button>
            <button onClick={() => setFilter("REJECTED")} style={{ ...filterButtonStyle, background: filter === "REJECTED" ? "var(--danger)" : "var(--surface-hover)", color: filter === "REJECTED" ? "white" : "var(--text-main)" }}>Respinse</button>
          </>
        ) : (
          <>
            <button onClick={() => setFilter("ALL")} style={{ ...filterButtonStyle, background: filter === "ALL" ? "var(--primary)" : "var(--surface-hover)", color: filter === "ALL" ? "white" : "var(--text-main)" }}>Toate vizibile</button>
            <button onClick={() => setFilter("MINE")} style={{ ...filterButtonStyle, background: filter === "MINE" ? "var(--primary)" : "var(--surface-hover)", color: filter === "MINE" ? "white" : "var(--text-main)" }}>Doar ale mele</button>
          </>
        )}

        <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginLeft: "0.5rem", paddingLeft: "1rem", borderLeft: "1px solid var(--border-color)" }}>
          <span style={{ fontSize: "0.8rem", fontWeight: 600, color: "var(--text-muted)", whiteSpace: "nowrap" }}>Fundal:</span>
          <select 
            value={activeBaseLayer} 
            onChange={(e) => setActiveBaseLayer(e.target.value)}
            style={{ 
              ...filterButtonStyle, 
              background: "var(--surface-hover)", 
              padding: "0.35rem 0.5rem",
              outline: "none"
            }}
          >
            <option value="OSM">Harta actuală</option>
            <option value="SATELLITE">Satelit</option>
            <option value="HISTORIC">Hartă istorică</option>
          </select>
        </div>
      </div>

      <MapContainer 
        center={[45.9432, 24.9668]} 
        zoom={7} 
        style={{ height: "100%", width: "100%" }}
      >
        <TileLayer
          attribution={
            activeBaseLayer === "OSM" ? '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' :
            activeBaseLayer === "SATELLITE" ? '&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' :
            '&copy; <a href="https://geo-spatial.org">geo-spatial.org</a>'
          }
          url={
            activeBaseLayer === "OSM" ? "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" :
            activeBaseLayer === "SATELLITE" ? "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}" :
            "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}"
          }
        />
        
        <MarkerClusterGroup chunkedLoading>
        {filteredEntries.map(entry => {
          const isOwner = entry.userId === currentUserId
          const isAdmin = userRole === "ADMIN"

          return (
            <Marker 
              key={entry.id} 
              position={[entry.latitude, entry.longitude]}
              icon={createStatusIcon(entry.status)}
            >
              <Popup>
                <div style={{ width: "240px", padding: "0.25rem" }}>
                  {entry.photos.length > 0 && (
                    <div style={{ marginBottom: "0.5rem" }}>
                      <PhotoCarousel 
                        photos={entry.photos} 
                        altText={entry.title} 
                        height="120px" 
                        borderRadius="4px" 
                      />
                    </div>
                  )}
                  
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.4rem" }}>
                    {(isAdmin || isOwner) ? (
                      <span style={{ 
                        fontSize: "0.7rem", 
                        fontWeight: 700, 
                        padding: "0.2rem 0.5rem", 
                        borderRadius: "999px",
                        background: entry.status === "APPROVED" ? "rgba(16,185,129,0.12)" : 
                                    entry.status === "REJECTED" ? "rgba(239,68,68,0.12)" : "rgba(245,158,11,0.12)",
                        color: entry.status === "APPROVED" ? "var(--success)" : 
                               entry.status === "REJECTED" ? "var(--danger)" : "var(--warning)",
                      }}>
                        {entry.status}
                      </span>
                    ) : (
                      <span style={{ 
                        fontSize: "0.7rem", 
                        fontWeight: 700, 
                        padding: "0.2rem 0.5rem", 
                        borderRadius: "999px",
                        background: "rgba(16, 185, 129, 0.12)",
                        color: "var(--success)",
                      }}>
                        Public
                      </span>
                    )}
                    <span style={{ fontSize: "0.75rem", color: "var(--text-muted)" }}>
                      {entry.city}
                    </span>
                  </div>


                  <h3 style={{ margin: "0 0 0.25rem 0", fontSize: "1.05rem", fontWeight: 700, lineHeight: 1.3 }}>{entry.title}</h3>
                  <p style={{ margin: "0 0 0.75rem 0", fontSize: "0.82rem", color: "var(--text-muted)", display: "flex", flexDirection: "column" }}>
                    <span>De: <strong>{entry.user.name || "Anonim"}</strong>{entry.user.class && ` (Cls a ${entry.user.class}-a)`}</span>
                  </p>
                  
                  <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
                    {/* Public details */}
                    <Link 
                      href={isAdmin ? `/admin/entry/${entry.id}` : `/entry/${entry.id}`} 
                      style={{ 
                        display: "flex", 
                        alignItems: "center", 
                        justifyContent: "center", 
                        gap: "0.4rem", 
                        background: "var(--surface-hover)", 
                        color: "var(--text-main)", 
                        padding: "0.5rem", 
                        borderRadius: "var(--radius-md)", 
                        textDecoration: "none", 
                        fontSize: "0.85rem", 
                        fontWeight: 600,
                        border: "1px solid var(--border-color)"
                      }}
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
                      Vezi detalii
                    </Link>

                    {/* Edit Option */}
                    {(isAdmin || isOwner) && (
                      <Link 
                        href={`/entry/${entry.id}/edit`} 
                        style={{ 
                          display: "flex", 
                          alignItems: "center", 
                          justifyContent: "center", 
                          gap: "0.4rem", 
                          background: "var(--surface-hover)", 
                          color: "var(--text-main)", 
                          padding: "0.5rem", 
                          borderRadius: "var(--radius-md)", 
                          textDecoration: "none", 
                          fontSize: "0.85rem", 
                          fontWeight: 600,
                          border: "1px solid var(--border-color)"
                        }}
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
                        Editează
                      </Link>
                    )}

                    {/* Admin Actions */}
                    {isAdmin && (
                      <div style={{ display: "flex", gap: "0.5rem", marginTop: "0.25rem" }}>
                        {entry.status !== "APPROVED" && (
                          <button
                            disabled={isPending}
                            onClick={() => handleStatusChange(entry.id, "APPROVED")}
                            style={{ 
                              flex: 1, 
                              background: "var(--success)", 
                              color: "white", 
                              border: "none", 
                              padding: "0.5rem", 
                              borderRadius: "var(--radius-md)", 
                              fontSize: "0.8rem", 
                              fontWeight: 700, 
                              cursor: "pointer",
                              opacity: isPending ? 0.6 : 1
                            }}
                          >
                            Aprobă
                          </button>
                        )}
                        {entry.status !== "REJECTED" && (
                          <button
                            disabled={isPending}
                            onClick={() => handleStatusChange(entry.id, "REJECTED")}
                            style={{ 
                              flex: 1, 
                              background: "var(--danger)", 
                              color: "white", 
                              border: "none", 
                              padding: "0.5rem", 
                              borderRadius: "var(--radius-md)", 
                              fontSize: "0.8rem", 
                              fontWeight: 700, 
                              cursor: "pointer",
                              opacity: isPending ? 0.6 : 1
                            }}
                          >
                            Respinge
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              </Popup>
            </Marker>
          )
        })}
        </MarkerClusterGroup>
      </MapContainer>
    </div>
  )
}
