import { db } from "@/lib/db"
import { notFound } from "next/navigation"
import Link from "next/link"
import { auth } from "@/lib/auth"
import { EntryPhotoGallery } from "@/components/ui/EntryPhotoGallery"

export default async function PublicEntryPage({ params }: { params: { id: string } }) {
  const { id } = await params

  const session = await auth()
  const userId = session?.user?.id
  const isAdmin = session?.user?.role === "ADMIN"

  const entry = await db.entry.findUnique({
    where: { id },
    include: {
      photos: true,
      user: { select: { name: true, class: true } },
    },
  })

  if (!entry) notFound()

  // Security check: only allow viewing if approved, or if user is owner/admin
  const isOwner = userId === entry.userId
  const isApproved = entry.status === "APPROVED"

  if (!isApproved && !isOwner && !isAdmin) {
    notFound()
  }

  return (
    <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh", maxWidth: "900px" }}>
      {/* Back to map */}
      <div style={{ marginBottom: "2rem" }}>
        <Link
          href={session ? "/dashboard/map" : "/"}
          style={{
            color: "var(--text-muted)",
            display: "inline-flex",
            alignItems: "center",
            gap: "0.35rem",
            textDecoration: "none",
            fontSize: "0.9rem",
          }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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 hartă
        </Link>
      </div>

      {/* Header */}
      <div style={{ marginBottom: "2rem" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "0.75rem", marginBottom: "0.75rem" }}>
          <span
            style={{
              padding: "0.2rem 0.75rem",
              borderRadius: "999px",
              fontSize: "0.78rem",
              fontWeight: 600,
              background: entry.status === "APPROVED" ? "rgba(16,185,129,0.1)" : 
                          entry.status === "REJECTED" ? "rgba(239, 68, 68, 0.1)" : "rgba(245, 158, 11, 0.1)",
              color: entry.status === "APPROVED" ? "var(--success)" : 
                     entry.status === "REJECTED" ? "var(--danger)" : "var(--warning)",
            }}
          >
            {entry.status === "APPROVED" ? "✓ APROBAT" : 
             entry.status === "REJECTED" ? "✗ RESPINS" : "⏳ ÎN AȘTEPTARE"}
          </span>
          <span style={{ fontSize: "0.85rem", color: "var(--text-muted)" }}>
            📍 {entry.city}, {entry.county}
          </span>
        </div>
        <h1 style={{ fontSize: "2rem", fontWeight: 700, marginBottom: "0.5rem" }}>{entry.title}</h1>
        <p style={{ color: "var(--text-muted)", fontSize: "1rem" }}>
          {entry.subjectName}
        </p>
        <div style={{ display: "flex", gap: "1.5rem", marginTop: "0.75rem", flexWrap: "wrap", fontSize: "0.88rem", color: "var(--text-muted)" }}>
          {(isAdmin || isOwner) && (
            <span>
              👤 Autor: <strong style={{ color: "var(--text-main)" }}>{entry.user.name || "Necunoscut"}</strong>
              {entry.user.class && `, Clasa a ${entry.user.class}-a`}
            </span>
          )}
          {entry.lmiRanCode && (
            <span>🏛 Cod LMI/RAN: <strong style={{ color: "var(--text-main)" }}>{entry.lmiRanCode}</strong></span>
          )}
          {entry.estimatedPeriod && (
            <span>📅 Perioadă: <strong style={{ color: "var(--text-main)" }}>{entry.estimatedPeriod}</strong></span>
          )}
        </div>
      </div>

      {/* Photos */}
      {entry.photos.length > 0 && (
        <div style={{ marginBottom: "2rem" }}>
          <EntryPhotoGallery photos={entry.photos} title={entry.title} isAdminView={false} />
        </div>
      )}

      {/* Content sections */}
      <div style={{ display: "grid", gap: "1.5rem" }}>
        {/* Location */}
        <div style={{ background: "var(--surface-color)", border: "1px solid var(--border-color)", borderRadius: "var(--radius-lg)", padding: "1.5rem" }}>
          <h2 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "1rem", color: "var(--primary)" }}>📍 Localizare</h2>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem", fontSize: "0.9rem" }}>
            <div>
              <span style={{ color: "var(--text-muted)" }}>Adresă:</span>
              <br /><strong>{entry.address}</strong>
            </div>
            <div>
              <span style={{ color: "var(--text-muted)" }}>Localitate / Județ:</span>
              <br /><strong>{entry.city}, {entry.county}</strong>
            </div>
            <div>
              <span style={{ color: "var(--text-muted)" }}>Coordonate GPS:</span>
              <br /><strong>{entry.latitude.toFixed(5)}, {entry.longitude.toFixed(5)}</strong>
            </div>
          </div>
        </div>

        {/* Motivation */}
        <div style={{ background: "var(--surface-color)", border: "1px solid var(--border-color)", borderRadius: "var(--radius-lg)", padding: "1.5rem" }}>
          <h2 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem", color: "var(--primary)" }}>💡 Motivație personală</h2>
          <p style={{ lineHeight: 1.7, color: "var(--text-main)" }}>{entry.motivation}</p>
        </div>

        {/* Context */}
        <div style={{ background: "var(--surface-color)", border: "1px solid var(--border-color)", borderRadius: "var(--radius-lg)", padding: "1.5rem" }}>
          <h2 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem", color: "var(--primary)" }}>🏙 Context urban / social / cultural</h2>
          <p style={{ lineHeight: 1.7, color: "var(--text-main)" }}>{entry.context}</p>
        </div>

        {/* Historical */}
        <div style={{ background: "var(--surface-color)", border: "1px solid var(--border-color)", borderRadius: "var(--radius-lg)", padding: "1.5rem" }}>
          <h2 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem", color: "var(--primary)" }}>📜 Descriere istorică / geografică</h2>
          <p style={{ lineHeight: 1.7, color: "var(--text-main)" }}>{entry.historicalDesc}</p>
        </div>

        {/* Sources */}
        {entry.bibliographicSources && (
          <div style={{ background: "var(--surface-color)", border: "1px solid var(--border-color)", borderRadius: "var(--radius-lg)", padding: "1.5rem" }}>
            <h2 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem", color: "var(--primary)" }}>📚 Surse bibliografice / web</h2>
            <p style={{ lineHeight: 1.7, color: "var(--text-main)", whiteSpace: "pre-wrap" }}>{entry.bibliographicSources}</p>
          </div>
        )}

        {/* Personal observations */}
        {entry.personalObservations && (
          <div style={{ background: "var(--surface-color)", border: "1px solid var(--border-color)", borderRadius: "var(--radius-lg)", padding: "1.5rem" }}>
            <h2 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem", color: "var(--primary)" }}>🔍 Observații personale</h2>
            <p style={{ lineHeight: 1.7, color: "var(--text-main)" }}>{entry.personalObservations}</p>
          </div>
        )}
      </div>

      {/* Footer back link */}
      <div style={{ marginTop: "3rem", textAlign: "center" }}>
        <Link
          href={session ? "/dashboard/map" : "/"}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: "0.5rem",
            padding: "0.75rem 2rem",
            background: "var(--primary)",
            color: "white",
            borderRadius: "var(--radius-md)",
            fontWeight: 600,
          }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polygon points="3 11 22 2 13 21 11 13 3 11" />
          </svg>
          Înapoi la harta Ro-VIBE
        </Link>
      </div>
    </main>
  )
}
