import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { redirect } from "next/navigation"
import Link from "next/link"
import { getCountiesForCommission, getStageForCommission } from "@/lib/commissions"
import { EntryPhotoGallery } from "@/components/ui/EntryPhotoGallery"
import { EvaluationForm } from "@/components/evaluator/EvaluationForm"
import type { EvaluationData } from "@/components/evaluator/EvaluationForm"

export default async function EvaluatorEntryPage({ params }: { params: { id: string } }) {
  const session = await auth()

  if (!session?.user || session.user.role !== "EVALUATOR") {
    redirect("/")
  }

  const { id } = await params;

  const entry = await db.entry.findUnique({
    where: { id },
    include: {
      user: {
        select: { name: true, email: true, class: true, county: 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="/evaluator" style={{ color: "var(--primary)", marginTop: "1rem", display: "inline-block" }}>Înapoi la Dashboard</Link>
      </main>
    )
  }

  // Security: verify this entry's author belongs to the evaluator's commission
  const commission = session.user.commission
  const counties = await getCountiesForCommission(commission)
  const userCounty = entry.user.county || ""
  if (!counties.includes(userCounty)) {
    return (
      <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh", textAlign: "center" }}>
        <h1>Acces interzis</h1>
        <p style={{ color: "var(--text-muted)" }}>Această lucrare nu este alocată comisiei tale.</p>
        <Link href="/evaluator" style={{ color: "var(--primary)", marginTop: "1rem", display: "inline-block" }}>Înapoi la Dashboard</Link>
      </main>
    )
  }

  // Security: verify entry stage matches commission stage
  const commissionStage = await getStageForCommission(commission)
  if (entry.stage !== commissionStage) {
    return (
      <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh", textAlign: "center" }}>
        <h1>Acces interzis</h1>
        <p style={{ color: "var(--text-muted)" }}>Această lucrare nu aparține etapei evaluate de comisia ta.</p>
        <Link href="/evaluator" style={{ color: "var(--primary)", marginTop: "1rem", display: "inline-block" }}>Înapoi la Dashboard</Link>
      </main>
    )
  }

  // Fetch existing evaluation by this evaluator for this entry
  const existingEval = await db.evaluation.findUnique({
    where: {
      entryId_evaluatorId: {
        entryId: id,
        evaluatorId: session.user.id,
      },
    },
  })

  // Check if this evaluator is frozen by admin
  const currentUser = await db.user.findUnique({
    where: { id: session.user.id },
    select: { evaluationsFrozen: true },
  })
  const isFrozen = currentUser?.evaluationsFrozen ?? false

  // Fetch all entry IDs in the same order as the dashboard (createdAt desc)
  // to determine prev/next navigation
  const allEntryIds = await db.entry.findMany({
    where: {
      deletedAt: null,
      ...(counties.length > 0 ? { user: { county: { in: counties } } } : { id: "__none__" }),
    },
    select: { id: true },
    orderBy: { createdAt: "desc" },
  })

  const currentIndex = allEntryIds.findIndex(e => e.id === id)
  const prevEntryId = currentIndex > 0 ? allEntryIds[currentIndex - 1].id : null
  const nextEntryId = currentIndex >= 0 && currentIndex < allEntryIds.length - 1 ? allEntryIds[currentIndex + 1].id : null
  const entryPosition = currentIndex >= 0 ? currentIndex + 1 : null
  const totalEntries = allEntryIds.length

  const evaluationData: EvaluationData | null = existingEval
    ? {
        relevance: existingEval.relevance,
        photoQuality: existingEval.photoQuality,
        originality: existingEval.originality,
        documentation: existingEval.documentation,
        gisIntegration: existingEval.gisIntegration,
        presentation: existingEval.presentation,
        motivation: existingEval.motivation,
        comment: existingEval.comment ?? "",
        status: existingEval.status as "DRAFT" | "FINAL",
      }
    : null

  return (
    <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh", maxWidth: "900px" }}>
      {/* Navigation */}
      <div style={{ marginBottom: "2rem", display: "flex", gap: "1rem", alignItems: "center", flexWrap: "wrap" }}>
        <Link href="/evaluator" 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>

        {/* Position indicator */}
        {entryPosition && (
          <span style={{
            fontSize: "0.78rem",
            padding: "0.2rem 0.6rem",
            borderRadius: "999px",
            background: "var(--surface-hover)",
            color: "var(--text-muted)",
            fontWeight: 500,
          }}>
            {entryPosition} / {totalEntries}
          </span>
        )}

        {/* Prev / Next navigation */}
        <div style={{ display: "flex", gap: "0.35rem", marginLeft: "auto" }}>
          {prevEntryId && (
            <Link
              href={`/evaluator/entry/${prevEntryId}`}
              title="Lucrarea anterioară"
              style={{
                padding: "0.4rem 0.65rem",
                borderRadius: "var(--radius-md)",
                border: "1px solid var(--border-color)",
                background: "var(--surface-color)",
                color: "var(--text-main)",
                display: "flex",
                alignItems: "center",
                textDecoration: "none",
                fontSize: "0.85rem",
                fontWeight: 500,
                transition: "background 0.15s",
              }}
            >
              <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="m15 18-6-6 6-6"/></svg>
              Ant.
            </Link>
          )}
          {nextEntryId && (
            <Link
              href={`/evaluator/entry/${nextEntryId}`}
              title="Lucrarea următoare"
              style={{
                padding: "0.4rem 0.65rem",
                borderRadius: "var(--radius-md)",
                border: "1px solid var(--primary)",
                background: "var(--primary)",
                color: "white",
                display: "flex",
                alignItems: "center",
                gap: "0.25rem",
                textDecoration: "none",
                fontSize: "0.85rem",
                fontWeight: 600,
                transition: "background 0.15s",
              }}
            >
              Urm.
              <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="m9 18 6-6-6-6"/></svg>
            </Link>
          )}
        </div>

        <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,
        }}>
          Status: {entry.status === "SUBMITTED" ? "DE EVALUAT" : entry.status === "APPROVED" ? "APROBAT" : "RESPINS"}
        </span>
      </div>

      {/* Main Content Card */}
      <div style={{ background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", overflow: "hidden", marginBottom: "2rem" }}>
        {/* Title */}
        <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>

        {/* Author & Location Grid */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "2rem", padding: "2rem" }}>
          {/* Author */}
          <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>
              {entry.user.class && <p><strong>Clasa:</strong> a {entry.user.class}-a</p>}
              <p><strong>Județ participant:</strong> {entry.user.county || "—"}</p>
              <p><strong>Data trimiterii:</strong> {new Date(entry.createdAt).toLocaleString("ro-RO")}</p>
            </div>
          </div>

          {/* Location */}
          <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 */}
        <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>
          <EntryPhotoGallery photos={entry.photos} title={entry.title} isAdminView={false} />
        </div>

        {/* Documentation */}
        <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>

      {/* Evaluation Form */}
      <EvaluationForm
        entryId={id}
        initialData={evaluationData}
        nextEntryId={nextEntryId}
        prevEntryId={prevEntryId}
        frozen={isFrozen}
      />
    </main>
  )
}

