import { auth } from "@/lib/auth"
import { db } from "@/lib/db"
import { redirect } from "next/navigation"
import Link from "next/link"
import { DashboardNav } from "@/components/ui/DashboardNav"
import { AdminEvaluationTable } from "@/components/admin/AdminEvaluationTable"
import { EvaluatorFreezePanel } from "@/components/admin/EvaluatorFreezePanel"

export default async function AdminEvaluationsPage() {
  const session = await auth()

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

  // Fetch all evaluations with evaluator and entry data
  const evaluations = await db.evaluation.findMany({
    include: {
      evaluator: {
        select: { name: true, email: true, commission: true },
      },
      entry: {
        select: {
          title: true,
          subjectName: true,
          city: true,
          county: true,
          stage: true,
          user: { select: { name: true, email: true } },
        },
      },
    },
    orderBy: { updatedAt: "desc" },
  })

  // Fetch unevaluated entries (entries with 0 evaluations)
  const unevaluatedEntries = await db.entry.findMany({
    where: {
      deletedAt: null,
      evaluations: { none: {} },
    },
    orderBy: { createdAt: "desc" },
    select: {
      id: true,
      title: true,
      subjectName: true,
      city: true,
      county: true,
      stage: true,
      createdAt: true,
      user: { select: { name: true, email: true, county: true } },
    },
  })

  // Total non-deleted entries for context
  const totalEntries = await db.entry.count({ where: { deletedAt: null } })

  // Stats
  const totalEvals = evaluations.length
  const draftEvals = evaluations.filter(e => e.status === "DRAFT").length
  const finalEvals = evaluations.filter(e => e.status === "FINAL").length
  const uniqueEntries = new Set(evaluations.map(e => e.entryId)).size
  const uniqueEvaluators = new Set(evaluations.map(e => e.evaluatorId)).size
  const unevaluatedCount = unevaluatedEntries.length

  // Avg score
  const avgScore = totalEvals > 0
    ? Math.round(evaluations.reduce((acc, e) =>
        acc + e.relevance + e.photoQuality + e.originality + e.documentation + e.gisIntegration + e.presentation + e.motivation, 0) / totalEvals)
    : 0

  // Serialize evaluations for client
  const serialized = evaluations.map(e => ({
    id: e.id,
    entryId: e.entryId,
    status: e.status,
    relevance: e.relevance,
    photoQuality: e.photoQuality,
    originality: e.originality,
    documentation: e.documentation,
    gisIntegration: e.gisIntegration,
    presentation: e.presentation,
    motivation: e.motivation,
    comment: e.comment,
    createdAt: e.createdAt.toISOString(),
    updatedAt: e.updatedAt.toISOString(),
    evaluator: e.evaluator,
    entry: e.entry,
  }))

  // Serialize unevaluated entries for client
  const serializedUnevaluated = unevaluatedEntries.map(e => ({
    id: e.id,
    title: e.title,
    subjectName: e.subjectName,
    city: e.city,
    county: e.county,
    stage: e.stage,
    createdAt: e.createdAt.toISOString(),
    user: e.user,
  }))

  // Fetch all evaluators with freeze status
  const evaluatorsRaw = await db.user.findMany({
    where: { role: "EVALUATOR", deletedAt: null },
    select: {
      id: true,
      name: true,
      email: true,
      commission: true,
      evaluationsFrozen: true,
      _count: { select: { evaluations: true } },
    },
    orderBy: { commission: "asc" },
  })
  const serializedEvaluators = evaluatorsRaw.map(e => ({
    ...e,
  }))

  return (
    <main className="container" style={{ padding: "3rem 1rem", minHeight: "100vh" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: "2rem", flexWrap: "wrap", gap: "1rem" }}>
        <div>
          <h1 style={{ fontSize: "2rem", marginBottom: "0.5rem" }}>Gestionare Evaluări</h1>
          <p style={{ color: "var(--text-muted)" }}>Vizualizare și administrare evaluări Ro-VIBE</p>
        </div>

        <div style={{ display: "flex", gap: "0.75rem", flexWrap: "wrap", alignItems: "center" }}>
          <Link
            href="/admin"
            style={{
              padding: "0.65rem 1.1rem",
              borderRadius: "var(--radius-md)",
              background: "var(--surface-color)",
              border: "1px solid var(--border-color)",
              color: "var(--text-main)",
              display: "flex",
              alignItems: "center",
              gap: "0.5rem",
              fontSize: "0.9rem",
              fontWeight: 500,
            }}
          >
            <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>
            Contribuții
          </Link>
          <Link
            href="/admin/statistics"
            style={{
              padding: "0.65rem 1.1rem",
              borderRadius: "var(--radius-md)",
              background: "var(--surface-color)",
              border: "1px solid var(--border-color)",
              color: "var(--text-main)",
              display: "flex",
              alignItems: "center",
              gap: "0.5rem",
              fontSize: "0.9rem",
              fontWeight: 500,
            }}
          >
            <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="M18 20V10"/><path d="M12 20V4"/><path d="M6 20v-6"/></svg>
            Statistici
          </Link>
          <DashboardNav userName={session.user.name} userEmail={session.user.email} />
        </div>
      </div>

      {/* Stats */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: "1rem", marginBottom: "2rem" }}>
        <div style={{ background: "var(--surface-color)", padding: "1.25rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", borderLeft: "4px solid var(--primary)" }}>
          <h3 style={{ color: "var(--text-muted)", fontSize: "0.82rem", marginBottom: "0.35rem" }}>Total Evaluări</h3>
          <p style={{ fontSize: "1.75rem", fontWeight: 700, color: "var(--text-main)" }}>{totalEvals}</p>
        </div>
        <div style={{ background: "var(--surface-color)", padding: "1.25rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", borderLeft: "4px solid #f59e0b" }}>
          <h3 style={{ color: "var(--text-muted)", fontSize: "0.82rem", marginBottom: "0.35rem" }}>Draft</h3>
          <p style={{ fontSize: "1.75rem", fontWeight: 700, color: "var(--text-main)" }}>{draftEvals}</p>
        </div>
        <div style={{ background: "var(--surface-color)", padding: "1.25rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", borderLeft: "4px solid var(--success)" }}>
          <h3 style={{ color: "var(--text-muted)", fontSize: "0.82rem", marginBottom: "0.35rem" }}>Finalizate</h3>
          <p style={{ fontSize: "1.75rem", fontWeight: 700, color: "var(--text-main)" }}>{finalEvals}</p>
        </div>
        <div style={{ background: "var(--surface-color)", padding: "1.25rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", borderLeft: "4px solid var(--secondary)" }}>
          <h3 style={{ color: "var(--text-muted)", fontSize: "0.82rem", marginBottom: "0.35rem" }}>Evaluate</h3>
          <p style={{ fontSize: "1.75rem", fontWeight: 700, color: "var(--text-main)" }}>{uniqueEntries}<span style={{ fontSize: "0.85rem", color: "var(--text-muted)", fontWeight: 400 }}> / {totalEntries}</span></p>
        </div>
        <div style={{ background: "var(--surface-color)", padding: "1.25rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", borderLeft: "4px solid var(--danger)" }}>
          <h3 style={{ color: "var(--text-muted)", fontSize: "0.82rem", marginBottom: "0.35rem" }}>Neevaluate</h3>
          <p style={{ fontSize: "1.75rem", fontWeight: 700, color: "var(--text-main)" }}>{unevaluatedCount}</p>
        </div>
        <div style={{ background: "var(--surface-color)", padding: "1.25rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", borderLeft: "4px solid #8b5cf6" }}>
          <h3 style={{ color: "var(--text-muted)", fontSize: "0.82rem", marginBottom: "0.35rem" }}>Evaluatori activi</h3>
          <p style={{ fontSize: "1.75rem", fontWeight: 700, color: "var(--text-main)" }}>{uniqueEvaluators}</p>
        </div>
        <div style={{ background: "var(--surface-color)", padding: "1.25rem", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", borderLeft: "4px solid var(--warning)" }}>
          <h3 style={{ color: "var(--text-muted)", fontSize: "0.82rem", marginBottom: "0.35rem" }}>Punctaj mediu</h3>
          <p style={{ fontSize: "1.75rem", fontWeight: 700, color: "var(--text-main)" }}>{avgScore}/100</p>
        </div>
      </div>

      {/* Evaluator Freeze Management */}
      <EvaluatorFreezePanel evaluators={serializedEvaluators} />

      <AdminEvaluationTable evaluations={serialized} unevaluatedEntries={serializedUnevaluated} />
    </main>
  )
}
