import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { redirect } from "next/navigation"
import Link from "next/link"
import { revalidatePath } from "next/cache"
import { DeleteEntryButton } from "@/components/admin/DeleteEntryButton"

export default async function AdminEntryPage({ params }: { params: { id: string } }) {
  const session = await auth()
  
  if (!session?.user || session.user.role !== "ADMIN") {
    redirect("/")
  }

  const { id } = await params;

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

  if (!entry) {
    return (
      <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh", textAlign: "center" }}>
        <h1>Intrarea nu a fost găsită</h1>
        <Link href="/admin" style={{ color: "var(--primary)", marginTop: "1rem", display: "inline-block" }}>Înapoi la Dashboard</Link>
      </main>
    )
  }

  // Server Actions for Approve/Reject
  const approveEntry = async () => {
    "use server"
    await db.entry.update({
      where: { id },
      data: { status: "APPROVED" }
    })
    revalidatePath("/admin")
    revalidatePath(`/admin/entry/${id}`)
    redirect("/admin")
  }

  const rejectEntry = async () => {
    "use server"
    await db.entry.update({
      where: { id },
      data: { status: "REJECTED" }
    })
    revalidatePath("/admin")
    revalidatePath(`/admin/entry/${id}`)
    redirect("/admin")
  }


  return (
    <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh", maxWidth: "900px" }}>
      <div style={{ marginBottom: "2rem", display: "flex", gap: "1rem", alignItems: "center" }}>
        <Link href="/admin" style={{ color: "var(--text-muted)", display: "flex", alignItems: "center", gap: "0.25rem", textDecoration: "none" }}>
          <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
        </Link>
        <span style={{ 
          fontSize: "0.75rem", padding: "0.25rem 0.6rem", borderRadius: "999px",
          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)",
          fontWeight: 600, marginLeft: "auto"
        }}>
          Status: {entry.status}
        </span>
      </div>

      <div style={{ background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", overflow: "hidden", marginBottom: "2rem" }}>
        <div style={{ padding: "2rem", borderBottom: "1px solid var(--border-color)" }}>
          <h1 style={{ fontSize: "2rem", marginBottom: "0.5rem" }}>{entry.title}</h1>
          <p style={{ color: "var(--text-muted)", fontSize: "1.1rem" }}>{entry.subjectName}</p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "2rem", padding: "2rem" }}>
          
          {/* Autor Details */}
          <div>
            <h3 style={{ fontSize: "1.1rem", borderBottom: "1px solid var(--border-color)", paddingBottom: "0.5rem", marginBottom: "1rem", color: "var(--primary)" }}>I. Autor</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
              <p><strong>Nume:</strong> {entry.user.name}</p>
              <p><strong>Clasa:</strong> a {entry.user.class}-a</p>
              <p><strong>Email:</strong> {entry.user.email}</p>
              <p><strong>Data trimiterii:</strong> {new Date(entry.createdAt).toLocaleString("ro-RO")}</p>
            </div>
          </div>

          {/* Location Details */}
          <div>
            <h3 style={{ fontSize: "1.1rem", borderBottom: "1px solid var(--border-color)", paddingBottom: "0.5rem", marginBottom: "1rem", color: "var(--primary)" }}>II. Locație</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
              <p><strong>Oraș / Județ:</strong> {entry.city}, {entry.county}</p>
              <p><strong>Adresă:</strong> {entry.address}</p>
              <p><strong>Coordonate:</strong> {entry.latitude}, {entry.longitude}</p>
              {entry.lmiRanCode && <p><strong>Cod LMI/RAN:</strong> {entry.lmiRanCode}</p>}
              {entry.estimatedPeriod && <p><strong>Perioadă:</strong> {entry.estimatedPeriod}</p>}
            </div>
          </div>
        </div>

        {/* Photos Section */}
        <div style={{ padding: "0 2rem 2rem 2rem" }}>
          <h3 style={{ fontSize: "1.1rem", borderBottom: "1px solid var(--border-color)", paddingBottom: "0.5rem", marginBottom: "1.25rem", color: "var(--primary)" }}>III. Fotografii ({entry.photos.length})</h3>
          
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gap: "1rem" }}>
            {entry.photos.map((photo: any) => (
              <div key={photo.id} style={{ border: "1px solid var(--border-color)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
                <div style={{ position: "relative" }}>
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={photo.url} alt={photo.filename} style={{ width: "100%", height: "200px", objectFit: "cover", display: "block" }} />
                  <a 
                    href={photo.url} 
                    download 
                    target="_blank"
                    style={{ position: "absolute", bottom: "0.5rem", right: "0.5rem", background: "rgba(0,0,0,0.6)", color: "white", padding: "0.4rem 0.6rem", borderRadius: "100px", fontSize: "0.75rem", textDecoration: "none", display: "flex", alignItems: "center", gap: "0.3rem", fontWeight: 500 }}
                  >
                    <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="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                    Descărcare (1:1)
                  </a>
                </div>
                <div style={{ padding: "0.75rem", fontSize: "0.85rem", background: "var(--surface-hover)" }}>
                  <p><strong>Data:</strong> {new Date(photo.dateOfCapture).toLocaleDateString("ro-RO")}</p>
                  {photo.equipment && <p><strong>Aparat:</strong> {photo.equipment}</p>}
                  {photo.technicalSettings && <p><strong>Setări:</strong> {photo.technicalSettings}</p>}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Documentation Section */}
        <div style={{ padding: "0 2rem 2rem 2rem" }}>
          <h3 style={{ fontSize: "1.1rem", borderBottom: "1px solid var(--border-color)", paddingBottom: "0.5rem", marginBottom: "1rem", color: "var(--primary)" }}>IV. Documentare</h3>
          
          <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
            <div>
              <p style={{ fontWeight: 600, marginBottom: "0.25rem" }}>Motivația personală</p>
              <p style={{ color: "var(--text-muted)", background: "var(--surface-hover)", padding: "1rem", borderRadius: "var(--radius-md)", fontSize: "0.95rem" }}>{entry.motivation}</p>
            </div>
            <div>
              <p style={{ fontWeight: 600, marginBottom: "0.25rem" }}>Context urban/social/cultural</p>
              <p style={{ color: "var(--text-muted)", background: "var(--surface-hover)", padding: "1rem", borderRadius: "var(--radius-md)", fontSize: "0.95rem" }}>{entry.context}</p>
            </div>
            <div>
              <p style={{ fontWeight: 600, marginBottom: "0.25rem" }}>Descriere istorică/geografică</p>
              <p style={{ color: "var(--text-muted)", background: "var(--surface-hover)", padding: "1rem", borderRadius: "var(--radius-md)", fontSize: "0.95rem" }}>{entry.historicalDesc}</p>
            </div>
            <div>
              <p style={{ fontWeight: 600, marginBottom: "0.25rem" }}>Surse bibliografice</p>
              <p style={{ color: "var(--text-muted)", background: "var(--surface-hover)", padding: "1rem", borderRadius: "var(--radius-md)", fontSize: "0.95rem" }}>{entry.bibliographicSources}</p>
            </div>
            {entry.personalObservations && (
              <div>
                <p style={{ fontWeight: 600, marginBottom: "0.25rem" }}>Alte observații</p>
                <p style={{ color: "var(--text-muted)", background: "var(--surface-hover)", padding: "1rem", borderRadius: "var(--radius-md)", fontSize: "0.95rem" }}>{entry.personalObservations}</p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div style={{ background: "var(--surface-color)", padding: "1.5rem 2rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", display: "flex", gap: "1rem", justifyContent: "flex-end", alignItems: "center" }}>
        
        <Link 
          href={`/entry/${entry.id}/edit`}
          style={{ 
            padding: "0.75rem 1.5rem", 
            borderRadius: "var(--radius-md)", 
            color: "var(--text-main)", 
            background: "var(--surface-hover)", 
            border: "1px solid var(--border-color)", 
            fontWeight: 500, 
            textDecoration: "none",
            fontSize: "0.95rem"
          }}
        >
          Editează conținut
        </Link>

        <DeleteEntryButton entryId={entry.id} entryTitle={entry.title} />

        {entry.status !== "REJECTED" && (
          <form action={rejectEntry}>
            <button style={{ padding: "0.75rem 1.5rem", borderRadius: "var(--radius-md)", color: "#fff", background: "var(--danger)", border: "none", fontWeight: 600, cursor: "pointer" }}>
              Respinge
            </button>
          </form>
        )}

        {entry.status !== "APPROVED" && (
          <form action={approveEntry}>
            <button style={{ padding: "0.75rem 1.5rem", borderRadius: "var(--radius-md)", color: "#fff", background: "var(--success)", border: "none", fontWeight: 600, cursor: "pointer" }}>
              Aprobă (Publică)
            </button>
          </form>
        )}
      </div>

    </main>
  )
}
