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 { StatisticsDashboard } from "@/components/admin/StatisticsDashboard"
import { getAllCommissions } from "@/lib/commissions"
import styles from "./statistics.module.css"

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

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

  // ── Fetch all data ─────────────────────────
  const [allEvaluations, allEntries, allEvaluators, allStudents] = await Promise.all([
    db.evaluation.findMany({
      include: {
        evaluator: {
          select: { id: true, name: true, email: true, commission: true, evaluationsFrozen: true },
        },
        entry: {
          select: {
            id: true,
            title: true,
            subjectName: true,
            city: true,
            county: true,
            stage: true,
            deletedAt: true,
            user: { select: { id: true, name: true, email: true, class: true, county: true } },
          },
        },
      },
    }),
    db.entry.findMany({
      where: { deletedAt: null },
      select: {
        id: true,
        title: true,
        subjectName: true,
        city: true,
        county: true,
        stage: true,
        user: { select: { id: true, name: true, email: true, class: true, county: true } },
      },
    }),
    db.user.findMany({
      where: { role: "EVALUATOR", deletedAt: null },
      select: {
        id: true,
        name: true,
        email: true,
        commission: true,
        evaluationsFrozen: true,
      },
    }),
    db.user.findMany({
      where: { role: "STUDENT", deletedAt: null },
      select: {
        id: true,
        name: true,
        email: true,
        class: true,
        county: true,
      },
    }),
  ])

  // Filter evaluations for non-deleted entries only
  const evaluations = allEvaluations.filter(e => !e.entry.deletedAt)

  // ── Helper: which commission owns a county ──
  const allCommissions = await getAllCommissions()
  const COMMISSIONS = allCommissions.map(c => c.code)
  const COMMISSION_COUNTIES: Record<string, string[]> = {}
  const COMMISSION_STAGES: Record<string, number> = {}
  for (const c of allCommissions) {
    COMMISSION_COUNTIES[c.code] = c.counties
    COMMISSION_STAGES[c.code] = c.stage
  }

  function getCommissionForCounty(county: string | null): string | null {
    if (!county) return null
    for (const [comm, counties] of Object.entries(COMMISSION_COUNTIES)) {
      if (counties.includes(county)) return comm
    }
    return null
  }

  // ── Helper: total score of an evaluation ────
  function evalTotal(e: typeof evaluations[number]): number {
    return e.relevance + e.photoQuality + e.originality + e.documentation +
      e.gisIntegration + e.presentation + e.motivation
  }

  // ── Build per-commission data ───────────────
  const commissionsData = COMMISSIONS.map(comm => {
    const counties = COMMISSION_COUNTIES[comm] || []
    const commStage = COMMISSION_STAGES[comm] || 1

    // Entries belonging to this commission (by student county AND entry stage)
    const commEntries = allEntries.filter(e =>
      counties.includes(e.user.county || "") && e.stage === commStage
    )

    // Entry IDs for this commission
    const commEntryIds = new Set(commEntries.map(e => e.id))

    // Evaluations for this commission's entries
    const commEvals = evaluations.filter(e => commEntryIds.has(e.entryId))

    // ── Rankings: group evals by entry, compute averages ──
    const entryEvalMap = new Map<string, typeof evaluations>()
    for (const ev of commEvals) {
      if (!entryEvalMap.has(ev.entryId)) entryEvalMap.set(ev.entryId, [])
      entryEvalMap.get(ev.entryId)!.push(ev)
    }

    const rankings = commEntries
      .map(entry => {
        const evals = entryEvalMap.get(entry.id) || []
        const count = evals.length
        const avg = count > 0
          ? evals.reduce((s, e) => s + evalTotal(e), 0) / count
          : 0

        const criteriaSum = {
          relevance: 0, photoQuality: 0, originality: 0,
          documentation: 0, gisIntegration: 0, presentation: 0, motivation: 0,
        }
        for (const e of evals) {
          criteriaSum.relevance += e.relevance
          criteriaSum.photoQuality += e.photoQuality
          criteriaSum.originality += e.originality
          criteriaSum.documentation += e.documentation
          criteriaSum.gisIntegration += e.gisIntegration
          criteriaSum.presentation += e.presentation
          criteriaSum.motivation += e.motivation
        }
        const criteriaAvg = {
          relevance: count > 0 ? criteriaSum.relevance / count : 0,
          photoQuality: count > 0 ? criteriaSum.photoQuality / count : 0,
          originality: count > 0 ? criteriaSum.originality / count : 0,
          documentation: count > 0 ? criteriaSum.documentation / count : 0,
          gisIntegration: count > 0 ? criteriaSum.gisIntegration / count : 0,
          presentation: count > 0 ? criteriaSum.presentation / count : 0,
          motivation: count > 0 ? criteriaSum.motivation / count : 0,
        }

        return {
          entryId: entry.id,
          title: entry.title,
          subjectName: entry.subjectName,
          studentName: entry.user.name || "—",
          studentEmail: entry.user.email || "—",
          county: entry.county,
          city: entry.city,
          className: entry.user.class,
          avgScore: avg,
          evalCount: count,
          criteria: criteriaAvg,
        }
      })
      .sort((a, b) => b.avgScore - a.avgScore)

    // ── Evaluator stats ──
    const commEvaluators = allEvaluators.filter(ev => ev.commission === comm)
    const evaluatorStats = commEvaluators.map(ev => {
      const evEvals = commEvals.filter(e => e.evaluatorId === ev.id)
      const finalEvals = evEvals.filter(e => e.status === "FINAL").length
      const draftEvals = evEvals.filter(e => e.status === "DRAFT").length
      const avgScore = evEvals.length > 0
        ? evEvals.reduce((s, e) => s + evalTotal(e), 0) / evEvals.length
        : 0

      return {
        id: ev.id,
        name: ev.name || "—",
        email: ev.email || "—",
        totalEvals: evEvals.length,
        finalEvals,
        draftEvals,
        avgScoreGiven: avgScore,
        frozen: ev.evaluationsFrozen,
      }
    })

    // ── Criteria averages (for radar chart) ──
    const totalCommEvals = commEvals.length
    const criteriaAvg = {
      relevance: totalCommEvals > 0 ? commEvals.reduce((s, e) => s + e.relevance, 0) / totalCommEvals : 0,
      photoQuality: totalCommEvals > 0 ? commEvals.reduce((s, e) => s + e.photoQuality, 0) / totalCommEvals : 0,
      originality: totalCommEvals > 0 ? commEvals.reduce((s, e) => s + e.originality, 0) / totalCommEvals : 0,
      documentation: totalCommEvals > 0 ? commEvals.reduce((s, e) => s + e.documentation, 0) / totalCommEvals : 0,
      gisIntegration: totalCommEvals > 0 ? commEvals.reduce((s, e) => s + e.gisIntegration, 0) / totalCommEvals : 0,
      presentation: totalCommEvals > 0 ? commEvals.reduce((s, e) => s + e.presentation, 0) / totalCommEvals : 0,
      motivation: totalCommEvals > 0 ? commEvals.reduce((s, e) => s + e.motivation, 0) / totalCommEvals : 0,
    }

    // ── Students in zone ──
    const commStudents = allStudents.filter(st => counties.includes(st.county || ""))
    const students = commStudents.map(st => {
      const studentEntries = commEntries.filter(e => e.user.id === st.id)
      const entryIds = studentEntries.map(e => e.id)
      const studentEvals = commEvals.filter(e => entryIds.includes(e.entryId))
      const hasFinal = studentEvals.some(e => e.status === "FINAL")
      const hasDraft = studentEvals.some(e => e.status === "DRAFT")

      return {
        id: st.id,
        name: st.name || "—",
        email: st.email || "—",
        county: st.county || "—",
        className: st.class,
        entryCount: studentEntries.length,
        evalCount: studentEvals.length,
        bestStatus: hasFinal ? "FINAL" as const : hasDraft ? "DRAFT" as const : "NONE" as const,
      }
    }).sort((a, b) => b.entryCount - a.entryCount)

    // Commission-level avg score
    const commAvgScore = totalCommEvals > 0
      ? commEvals.reduce((s, e) => s + evalTotal(e), 0) / totalCommEvals
      : 0

    // ── County breakdown ──
    const countyBreakdown = counties.map(county => {
      const countyEntries = commEntries.filter(e => e.user.county === county)
      const countyEntryIds = new Set(countyEntries.map(e => e.id))
      const countyEvals = commEvals.filter(e => countyEntryIds.has(e.entryId))
      const countyStudents = allStudents.filter(st => st.county === county)
      const evaluatedEntryIds = new Set(countyEvals.map(e => e.entryId))
      const countyAvg = countyEvals.length > 0
        ? countyEvals.reduce((s, e) => s + evalTotal(e), 0) / countyEvals.length
        : 0
      const countyFinal = countyEvals.filter(e => e.status === "FINAL").length

      // Top entry in this county
      let topEntry: { title: string; studentName: string; avgScore: number } | null = null
      if (countyEntries.length > 0) {
        const ranked = countyEntries.map(entry => {
          const evals = entryEvalMap.get(entry.id) || []
          const avg = evals.length > 0
            ? evals.reduce((s, e) => s + evalTotal(e), 0) / evals.length
            : 0
          return { title: entry.title, studentName: entry.user.name || "—", avgScore: avg }
        }).sort((a, b) => b.avgScore - a.avgScore)
        if (ranked[0] && ranked[0].avgScore > 0) topEntry = ranked[0]
      }

      return {
        county,
        totalEntries: countyEntries.length,
        totalEvaluations: countyEvals.length,
        evaluatedEntries: evaluatedEntryIds.size,
        totalStudents: countyStudents.length,
        avgScore: countyAvg,
        finalEvals: countyFinal,
        completionRate: countyEntries.length > 0
          ? (evaluatedEntryIds.size / countyEntries.length) * 100
          : 0,
        topEntry,
      }
    }).sort((a, b) => b.totalEntries - a.totalEntries)

    return {
      commission: comm,
      counties,
      stage: commStage,
      totalEntries: commEntries.length,
      totalEvaluations: totalCommEvals,
      avgScore: commAvgScore,
      rankings,
      evaluators: evaluatorStats,
      students,
      criteriaAvg,
      countyBreakdown,
    }
  })

  // ── Global stats ────────────────────────────
  const totalEvaluations = evaluations.length
  const uniqueEvaluatedEntries = new Set(evaluations.map(e => e.entryId)).size
  const uniqueEvaluators = new Set(evaluations.map(e => e.evaluatorId)).size
  const globalAvgScore = totalEvaluations > 0
    ? evaluations.reduce((s, e) => s + evalTotal(e), 0) / totalEvaluations
    : 0
  const completionRate = allEntries.length > 0
    ? (uniqueEvaluatedEntries / allEntries.length) * 100
    : 0

  const globalStats = {
    totalEvaluations,
    totalEntries: uniqueEvaluatedEntries,
    totalEvaluators: uniqueEvaluators,
    avgScore: globalAvgScore,
    completionRate,
  }

  return (
    <main className={`container ${styles.page}`}>
      {/* Header */}
      <div className={styles.header}>
        <div>
          <h1 className={styles.headerTitle}>Statistici Evaluări</h1>
          <p className={styles.headerSub}>
            Analiză detaliată pe comisii, clasamente și performanță evaluatori
          </p>
        </div>

        <div className={styles.headerActions}>
          <Link href="/admin/evaluations" className={styles.backBtn}>
            <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>
            Evaluări
          </Link>
          <Link href="/admin" className={styles.backBtn}>
            <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>
          <DashboardNav userName={session.user.name} userEmail={session.user.email} />
        </div>
      </div>

      <StatisticsDashboard globalStats={globalStats} commissions={commissionsData} />
    </main>
  )
}
