import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { redirect } from "next/navigation"
import DashboardMap from "@/components/map/DashboardMap"
import Link from "next/link"

export default async function DashboardMapPage() {
  const session = await auth()
  
  if (!session?.user) {
    redirect("/login")
  }

  const userRole = session.user.role as "ADMIN" | "STUDENT" | "TESTER"
  const currentUserId = session.user.id!

  const entries = await db.entry.findMany({
    where: userRole === "ADMIN" ? { deletedAt: null } : {
      deletedAt: null,
      OR: [
        { userId: currentUserId }, // Own entries (any status)
        { status: "APPROVED" }     // Other people's approved entries
      ]
    },
    include: {
      photos: true,
      user: {
        select: {
          name: true,
          class: true
        }
      }
    },
    orderBy: {
      createdAt: 'desc'
    }
  })

  // Evită căderile de hartă (crash Leaflet) excluzând intrările cu coordonate invalide/NaN
  const validEntries = entries.filter(e => 
    e.latitude != null && !Number.isNaN(e.latitude) && 
    e.longitude != null && !Number.isNaN(e.longitude)
  )

  const backHref = userRole === "ADMIN" ? "/admin" : "/dashboard"

  return (
    <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "2rem", flexWrap: "wrap", gap: "1rem" }}>
        <div>
          <h1 style={{ fontSize: "2rem", marginBottom: "0.5rem" }}>Hartă Interactivă</h1>
          <p style={{ color: "var(--text-muted)" }}>Explorează și gestionează toate contribuțiile Ro-VIBE</p>
        </div>
        
        <Link 
          href={backHref}
          style={{ 
            backgroundColor: "var(--surface-color)", 
            color: "var(--text-main)", 
            padding: "0.65rem 1.1rem", 
            borderRadius: "var(--radius-md)",
            fontWeight: 600,
            display: "flex",
            alignItems: "center",
            gap: "0.5rem",
            fontSize: "0.9rem",
            border: "1px solid var(--border-color)",
            textDecoration: "none"
          }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
          Înapoi la Dashboard
        </Link>
      </div>

      <DashboardMap 
        entries={validEntries as any} 
        userRole={userRole} 
        currentUserId={currentUserId} 
      />

      {userRole === "ADMIN" && (
        <div style={{ marginTop: "1.5rem", display: "flex", gap: "1.5rem", flexWrap: "wrap", justifyContent: "center" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontSize: "0.85rem" }}>
            <div style={{ width: "12px", height: "12px", background: "var(--success)", borderRadius: "50%", border: "2px solid white", boxShadow: "0 0 0 1px var(--border-color)" }}></div>
            <span>Aprobate</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontSize: "0.85rem" }}>
            <div style={{ width: "12px", height: "12px", background: "var(--warning)", borderRadius: "50%", border: "2px solid white", boxShadow: "0 0 0 1px var(--border-color)" }}></div>
            <span>În așteptare</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontSize: "0.85rem" }}>
            <div style={{ width: "12px", height: "12px", background: "var(--danger)", borderRadius: "50%", border: "2px solid white", boxShadow: "0 0 0 1px var(--border-color)" }}></div>
            <span>Respinse</span>
          </div>
        </div>
      )}
    </main>
  )
}
