"use client"

import { useState, useMemo } from "react"
import { useRouter } from "next/navigation"
import { bulkDeleteEvaluationsAction, resetEvaluationToFraftAction } from "@/app/admin/actions"
import { getCommissionDisplayNameSync } from "@/lib/commissions-client"

type Evaluation = {
  id: string
  entryId: string
  status: string
  relevance: number
  photoQuality: number
  originality: number
  documentation: number
  gisIntegration: number
  presentation: number
  motivation: number
  comment: string | null
  createdAt: string
  updatedAt: string
  evaluator: { name: string | null; email: string | null; commission: string | null }
  entry: {
    title: string
    subjectName: string
    city: string
    county: string
    stage: number
    user: { name: string | null; email: string | null }
  }
}

function getTotal(e: Evaluation): number {
  return e.relevance + e.photoQuality + e.originality + e.documentation + e.gisIntegration + e.presentation + e.motivation
}

type UnevaluatedEntry = {
  id: string
  title: string
  subjectName: string
  city: string
  county: string
  stage: number
  createdAt: string
  user: { name: string | null; email: string | null; county: string | null }
}

type ViewMode = "evaluations" | "byEntry" | "unevaluated"
type StatusFilter = "ALL" | "DRAFT" | "FINAL"
type StageFilter = "ALL" | 1 | 2
type SortCol = "entry" | "student" | "evaluator" | "commission" | "score" | "status" | "updatedAt"

export function AdminEvaluationTable({ evaluations, unevaluatedEntries }: { evaluations: Evaluation[]; unevaluatedEntries: UnevaluatedEntry[] }) {
  const [viewMode, setViewMode] = useState<ViewMode>("byEntry")
  const router = useRouter()
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [isDeleting, setIsDeleting] = useState(false)
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("ALL")
  const [stageFilter, setStageFilter] = useState<StageFilter>("ALL")
  const [sortCol, setSortCol] = useState<SortCol>("updatedAt")
  const [sortAsc, setSortAsc] = useState(false)
  const [expandedId, setExpandedId] = useState<string | null>(null)

  const filtered = useMemo(() => {
    return evaluations.filter(ev => {
      if (statusFilter !== "ALL" && ev.status !== statusFilter) return false
      if (stageFilter !== "ALL" && ev.entry.stage !== stageFilter) return false
      if (searchTerm) {
        const term = searchTerm.toLowerCase()
        const fields = [
          ev.entry.title,
          ev.entry.subjectName,
          ev.entry.city,
          ev.entry.county,
          ev.entry.user.name,
          ev.evaluator.name,
          ev.evaluator.email,
          ev.evaluator.commission,
          ev.status,
          String(getTotal(ev)),
          new Date(ev.updatedAt).toLocaleDateString("ro-RO"),
        ]
        if (!fields.some(f => (f || "").toLowerCase().includes(term))) return false
      }
      return true
    })
  }, [evaluations, statusFilter, stageFilter, searchTerm])

  const filteredUnevaluated = useMemo(() => {
    if (stageFilter === "ALL") return unevaluatedEntries
    return unevaluatedEntries.filter(e => e.stage === stageFilter)
  }, [unevaluatedEntries, stageFilter])

  const filteredByEntryEvals = useMemo(() => {
    if (stageFilter === "ALL") return evaluations
    return evaluations.filter(ev => ev.entry.stage === stageFilter)
  }, [evaluations, stageFilter])

  const sorted = useMemo(() => {
    return [...filtered].sort((a, b) => {
      let aVal: any, bVal: any
      switch (sortCol) {
        case "entry": aVal = a.entry.title; bVal = b.entry.title; break
        case "student": aVal = a.entry.user.name; bVal = b.entry.user.name; break
        case "evaluator": aVal = a.evaluator.name || a.evaluator.email; bVal = b.evaluator.name || b.evaluator.email; break
        case "commission": aVal = a.evaluator.commission; bVal = b.evaluator.commission; break
        case "score": aVal = getTotal(a); bVal = getTotal(b); break
        case "status": aVal = a.status; bVal = b.status; break
        case "updatedAt": aVal = new Date(a.updatedAt).getTime(); bVal = new Date(b.updatedAt).getTime(); break
      }
      if (aVal === bVal) return 0
      if (aVal == null) return 1
      if (bVal == null) return -1
      if (typeof aVal === "string" && typeof bVal === "string") return sortAsc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
      return sortAsc ? (aVal < bVal ? -1 : 1) : (aVal > bVal ? -1 : 1)
    })
  }, [filtered, sortCol, sortAsc])

  const handleSort = (col: SortCol) => {
    if (sortCol === col) setSortAsc(!sortAsc)
    else { setSortCol(col); setSortAsc(col === "updatedAt" ? false : true) }
  }

  const SortIndicator = ({ col }: { col: SortCol }) => {
    if (sortCol !== col) return <span style={{ marginLeft: "0.25rem", opacity: 0.3 }}>⇅</span>
    return <span style={{ marginLeft: "0.25rem", color: "var(--primary)" }}>{sortAsc ? "↑" : "↓"}</span>
  }

  const handleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      const newSet = new Set(selectedIds)
      sorted.forEach(s => newSet.add(s.id))
      setSelectedIds(newSet)
    } else {
      const newSet = new Set(selectedIds)
      sorted.forEach(s => newSet.delete(s.id))
      setSelectedIds(newSet)
    }
  }

  const handleSelectOne = (id: string) => {
    const newSet = new Set(selectedIds)
    if (newSet.has(id)) newSet.delete(id)
    else newSet.add(id)
    setSelectedIds(newSet)
  }

  const handleDeleteSelected = async () => {
    if (selectedIds.size === 0) return
    if (!window.confirm(`Ești sigur că vrei să ștergi ${selectedIds.size} evaluări? Acțiunea este ireversibilă.`)) return
    setIsDeleting(true)
    try {
      await bulkDeleteEvaluationsAction(Array.from(selectedIds))
      setSelectedIds(new Set())
      router.refresh()
    } catch {
      alert("Eroare la ștergere.")
    } finally {
      setIsDeleting(false)
    }
  }

  const handleResetToFraft = async (id: string) => {
    if (!window.confirm("Resetezi evaluarea la DRAFT? Evaluatorul va putea modifica punctajele.")) return
    try {
      await resetEvaluationToFraftAction(id)
      router.refresh()
    } catch {
      alert("Eroare la resetare.")
    }
  }

  const handleDeleteOne = async (id: string) => {
    if (!window.confirm("Ești sigur că vrei să ștergi această evaluare? Acțiunea este ireversibilă.")) return
    try {
      await bulkDeleteEvaluationsAction([id])
      router.refresh()
    } catch {
      alert("Eroare la ștergere.")
    }
  }

  const isAllSelected = sorted.length > 0 && sorted.every(s => selectedIds.has(s.id))
  const isIndeterminate = sorted.some(s => selectedIds.has(s.id)) && !isAllSelected

  const FILTER_PILLS: { key: StatusFilter; label: string }[] = [
    { key: "ALL", label: "Toate" },
    { key: "DRAFT", label: "Draft" },
    { key: "FINAL", label: "Finalizate" },
  ]

  return (
    <>
      <style>{`
        .sortable-header { transition: background-color 0.2s ease, color 0.2s ease; }
        .sortable-header:hover { background-color: var(--primary-light); color: var(--primary) !important; }
      `}</style>

      {/* View mode toggle */}
      <div style={{ display: "flex", gap: "0", marginBottom: "1rem", borderRadius: "var(--radius-md)", overflow: "hidden", border: "1px solid var(--border-color)", width: "fit-content" }}>
        <button
          onClick={() => setViewMode("byEntry")}
          style={{
            padding: "0.55rem 1.25rem",
            border: "none",
            background: viewMode === "byEntry" ? "var(--primary)" : "var(--surface-color)",
            color: viewMode === "byEntry" ? "white" : "var(--text-main)",
            fontSize: "0.88rem",
            fontWeight: viewMode === "byEntry" ? 600 : 400,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            gap: "0.4rem",
            borderRight: "1px solid var(--border-color)",
          }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>
          Per contribuție
        </button>
        <button
          onClick={() => setViewMode("evaluations")}
          style={{
            padding: "0.55rem 1.25rem",
            border: "none",
            background: viewMode === "evaluations" ? "var(--primary)" : "var(--surface-color)",
            color: viewMode === "evaluations" ? "white" : "var(--text-main)",
            fontSize: "0.88rem",
            fontWeight: viewMode === "evaluations" ? 600 : 400,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            gap: "0.4rem",
            borderRight: "1px solid var(--border-color)",
          }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
          Evaluări individuale ({evaluations.length})
        </button>
        <button
          onClick={() => setViewMode("unevaluated")}
          style={{
            padding: "0.55rem 1.25rem",
            border: "none",
            background: viewMode === "unevaluated" ? "var(--danger)" : "var(--surface-color)",
            color: viewMode === "unevaluated" ? "white" : "var(--text-main)",
            fontSize: "0.88rem",
            fontWeight: viewMode === "unevaluated" ? 600 : 400,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            gap: "0.4rem",
          }}
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
          Neevaluate ({filteredUnevaluated.length})
        </button>
      </div>

      {/* Stage filter */}
      <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem", alignItems: "center" }}>
        <span style={{ fontSize: "0.9rem", color: "var(--text-muted)", fontWeight: 500, marginRight: "0.25rem" }}>Etapă:</span>
        {(["ALL", 1, 2] as StageFilter[]).map(sf => (
          <button
            key={String(sf)}
            onClick={() => setStageFilter(sf)}
            style={{
              padding: "0.4rem 0.85rem",
              borderRadius: "999px",
              border: "1px solid",
              background: stageFilter === sf ? (sf === 2 ? "#d97706" : "var(--primary)") : "var(--surface-color)",
              color: stageFilter === sf ? "white" : "var(--text-main)",
              borderColor: stageFilter === sf ? (sf === 2 ? "#d97706" : "var(--primary)") : "var(--border-color)",
              fontSize: "0.85rem",
              fontWeight: stageFilter === sf ? 600 : 400,
              cursor: "pointer",
            }}
          >
            {sf === "ALL" ? "Toate" : `Etapa ${sf}`}
          </button>
        ))}
      </div>

      {viewMode === "unevaluated" ? (
        <UnevaluatedView entries={filteredUnevaluated} />
      ) : viewMode === "byEntry" ? (
        <ByEntryView evaluations={filteredByEntryEvals} />
      ) : (
        <>

      {/* Filter bar */}
      <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem", flexWrap: "wrap", alignItems: "center" }}>
        <span style={{ fontSize: "0.9rem", color: "var(--text-muted)", fontWeight: 500, marginRight: "0.5rem" }}>Status:</span>
        {FILTER_PILLS.map(fp => (
          <button
            key={fp.key}
            onClick={() => setStatusFilter(fp.key)}
            style={{
              padding: "0.4rem 0.8rem",
              borderRadius: "999px",
              border: "1px solid",
              background: statusFilter === fp.key ? "var(--primary)" : "var(--surface-color)",
              color: statusFilter === fp.key ? "white" : "var(--text-main)",
              borderColor: statusFilter === fp.key ? "var(--primary)" : "var(--border-color)",
              fontSize: "0.85rem",
              fontWeight: statusFilter === fp.key ? 600 : 400,
              cursor: "pointer",
            }}
          >
            {fp.label}
          </button>
        ))}
      </div>

      <div style={{ background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", overflow: "hidden" }}>
        {/* Header */}
        <div style={{ padding: "1.25rem 1.5rem", borderBottom: "1px solid var(--border-color)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "1rem" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "1rem", flexWrap: "wrap" }}>
            <h2 style={{ fontSize: "1.15rem", fontWeight: 600, display: "flex", alignItems: "center", gap: "0.5rem", margin: 0 }}>
              Evaluări ({sorted.length})
              {selectedIds.size > 0 && (
                <span style={{ fontSize: "0.85rem", background: "var(--primary-light)", color: "var(--primary)", padding: "0.2rem 0.6rem", borderRadius: "999px" }}>
                  {selectedIds.size} selectate
                </span>
              )}
            </h2>
            <input
              type="search"
              placeholder="Caută lucrare, evaluator, comisie, punctaj…"
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              style={{
                padding: "0.4rem 0.8rem",
                borderRadius: "var(--radius-sm)",
                border: "1px solid var(--border-color)",
                background: "var(--surface-hover)",
                color: "var(--text-main)",
                fontSize: "0.85rem",
                minWidth: "280px",
              }}
            />
          </div>

          {selectedIds.size > 0 && (
            <div style={{ display: "flex", gap: "0.75rem", alignItems: "center" }}>
              <button
                onClick={() => setSelectedIds(new Set())}
                style={{ padding: "0.4rem 0.75rem", fontSize: "0.85rem", background: "none", border: "1px solid var(--border-color)", borderRadius: "var(--radius-sm)", cursor: "pointer", color: "var(--text-main)" }}
              >
                Deselectează
              </button>
              <button
                onClick={handleDeleteSelected}
                disabled={isDeleting}
                style={{ padding: "0.4rem 0.75rem", fontSize: "0.85rem", background: "var(--danger)", color: "white", border: "none", borderRadius: "var(--radius-sm)", cursor: isDeleting ? "wait" : "pointer", fontWeight: 500, display: "flex", alignItems: "center", gap: "0.3rem", opacity: isDeleting ? 0.6 : 1 }}
              >
                <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="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
                {isDeleting ? "Se șterg…" : "Șterge selectate"}
              </button>
            </div>
          )}
        </div>

        {/* Table */}
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", textAlign: "left" }}>
            <thead>
              <tr style={{ background: "var(--surface-hover)" }}>
                <th style={{ padding: "0.85rem 1.5rem", width: "40px" }}>
                  <input
                    type="checkbox"
                    checked={isAllSelected}
                    ref={input => { if (input) input.indeterminate = isIndeterminate }}
                    onChange={handleSelectAll}
                    style={{ cursor: "pointer", width: "16px", height: "16px", accentColor: "var(--primary)" }}
                  />
                </th>
                {[
                  { key: "entry", label: "Lucrare" },
                  { key: "student", label: "Elev" },
                  { key: "evaluator", label: "Evaluator" },
                  { key: "commission", label: "Comisie" },
                  { key: "score", label: "Punctaj" },
                  { key: "status", label: "Status" },
                  { key: "updatedAt", label: "Data" },
                ].map(h => (
                  <th
                    key={h.key}
                    className="sortable-header"
                    onClick={() => handleSort(h.key as SortCol)}
                    style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase", cursor: "pointer", userSelect: "none", whiteSpace: "nowrap" }}
                  >
                    {h.label} <SortIndicator col={h.key as SortCol} />
                  </th>
                ))}
                <th style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase", textAlign: "right" }}>Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              {sorted.map(ev => {
                const total = getTotal(ev)
                const isExpanded = expandedId === ev.id
                return (
                  <>
                    <tr
                      key={ev.id}
                      style={{
                        borderBottom: "1px solid var(--border-color)",
                        background: selectedIds.has(ev.id) ? "var(--surface-hover)" : "transparent",
                      }}
                    >
                      <td style={{ padding: "0.85rem 1.5rem" }}>
                        <input
                          type="checkbox"
                          checked={selectedIds.has(ev.id)}
                          onChange={() => handleSelectOne(ev.id)}
                          style={{ cursor: "pointer", width: "16px", height: "16px", accentColor: "var(--primary)" }}
                        />
                      </td>
                      <td style={{ padding: "0.85rem 1rem" }}>
                        <div style={{ fontWeight: 500, color: "var(--text-main)", marginBottom: "0.15rem", maxWidth: "200px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{ev.entry.title}</div>
                        <div style={{ fontSize: "0.78rem", color: "var(--text-muted)" }}>{ev.entry.city}, {ev.entry.county}</div>
                      </td>
                      <td style={{ padding: "0.85rem 1rem", fontSize: "0.88rem", color: "var(--text-muted)" }}>{ev.entry.user.name || "—"}</td>
                      <td style={{ padding: "0.85rem 1rem" }}>
                        <div style={{ fontWeight: 500, color: "var(--text-main)", marginBottom: "0.15rem" }}>{ev.evaluator.name || ev.evaluator.email}</div>
                      </td>
                      <td style={{ padding: "0.85rem 1rem", textAlign: "center" }}>
                        <span style={{
                          fontSize: "0.78rem", padding: "0.2rem 0.5rem", borderRadius: "999px",
                          background: "rgba(79, 70, 229, 0.08)", color: "var(--primary)", fontWeight: 700,
                        }}>
                          {getCommissionDisplayNameSync(ev.evaluator.commission)}
                        </span>
                      </td>
                      <td style={{ padding: "0.85rem 1rem" }}>
                        <span style={{
                          fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "1.1rem",
                          color: total >= 75 ? "var(--success)" : total >= 50 ? "var(--primary)" : total >= 25 ? "#d97706" : "var(--danger)",
                        }}>
                          {total}
                        </span>
                        <span style={{ color: "var(--text-muted)", fontSize: "0.82rem" }}>/100</span>
                      </td>
                      <td style={{ padding: "0.85rem 1rem" }}>
                        <span style={{
                          fontSize: "0.72rem", padding: "0.2rem 0.5rem", borderRadius: "999px",
                          background: ev.status === "FINAL" ? "rgba(16, 185, 129, 0.1)" : "rgba(245, 158, 11, 0.1)",
                          color: ev.status === "FINAL" ? "var(--success)" : "#d97706",
                          fontWeight: 600,
                        }}>
                          {ev.status === "FINAL" ? "🔒 FINAL" : "✎ DRAFT"}
                        </span>
                      </td>
                      <td style={{ padding: "0.85rem 1rem", fontSize: "0.82rem", color: "var(--text-muted)", whiteSpace: "nowrap" }}>
                        {new Date(ev.updatedAt).toLocaleDateString("ro-RO")}
                      </td>
                      <td style={{ padding: "0.85rem 1rem", textAlign: "right", whiteSpace: "nowrap" }}>
                        <button
                          onClick={() => setExpandedId(isExpanded ? null : ev.id)}
                          title="Detalii punctaje"
                          style={{ padding: "0.3rem 0.5rem", borderRadius: "var(--radius-sm)", background: "var(--primary-light)", color: "var(--primary)", border: "none", cursor: "pointer", marginRight: "0.35rem", fontSize: "0.8rem" }}
                        >
                          {isExpanded ? "▲" : "▼"}
                        </button>
                        {ev.status === "FINAL" && (
                          <button
                            onClick={() => handleResetToFraft(ev.id)}
                            title="Resetează la Draft"
                            style={{ padding: "0.3rem 0.5rem", borderRadius: "var(--radius-sm)", background: "rgba(245, 158, 11, 0.1)", color: "#d97706", border: "none", cursor: "pointer", marginRight: "0.35rem", fontSize: "0.78rem" }}
                          >
                            ↩ Draft
                          </button>
                        )}
                        <button
                          onClick={() => handleDeleteOne(ev.id)}
                          title="Șterge evaluarea"
                          style={{ padding: "0.3rem 0.5rem", borderRadius: "var(--radius-sm)", background: "rgba(239, 68, 68, 0.08)", color: "var(--danger)", border: "none", cursor: "pointer", fontSize: "0.78rem" }}
                        >
                          🗑
                        </button>
                      </td>
                    </tr>

                    {/* Expanded detail row */}
                    {isExpanded && (
                      <tr key={`${ev.id}-detail`} style={{ borderBottom: "1px solid var(--border-color)", background: "var(--surface-hover)" }}>
                        <td colSpan={9} style={{ padding: "1rem 1.5rem" }}>
                          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: "0.75rem", marginBottom: ev.comment ? "0.75rem" : 0 }}>
                            {[
                              { label: "1. Relevanță", val: ev.relevance, max: 15 },
                              { label: "2. Fotografie", val: ev.photoQuality, max: 25 },
                              { label: "3. Originalitate", val: ev.originality, max: 10 },
                              { label: "4. Documentare", val: ev.documentation, max: 20 },
                              { label: "5. Integrare GIS", val: ev.gisIntegration, max: 10 },
                              { label: "6. Prezentare", val: ev.presentation, max: 10 },
                              { label: "7. Motivație", val: ev.motivation, max: 10 },
                            ].map(c => {
                              const pct = c.val / c.max
                              return (
                                <div key={c.label} style={{ background: "var(--surface-color)", padding: "0.75rem", borderRadius: "var(--radius-md)", border: "1px solid var(--border-color)" }}>
                                  <div style={{ fontSize: "0.78rem", color: "var(--text-muted)", marginBottom: "0.35rem" }}>{c.label}</div>
                                  <div style={{ display: "flex", alignItems: "baseline", gap: "0.25rem" }}>
                                    <span style={{
                                      fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "1.25rem",
                                      color: pct >= 0.75 ? "var(--success)" : pct >= 0.5 ? "var(--primary)" : pct >= 0.25 ? "#d97706" : "var(--danger)",
                                    }}>
                                      {c.val}
                                    </span>
                                    <span style={{ fontSize: "0.78rem", color: "var(--text-muted)" }}>/ {c.max}</span>
                                  </div>
                                  <div style={{ height: "3px", borderRadius: "2px", background: "var(--border-color)", marginTop: "0.35rem" }}>
                                    <div style={{
                                      height: "100%", borderRadius: "2px", width: `${pct * 100}%`,
                                      background: pct >= 0.75 ? "var(--success)" : pct >= 0.5 ? "var(--primary)" : pct >= 0.25 ? "#d97706" : "var(--danger)",
                                      transition: "width 0.3s",
                                    }} />
                                  </div>
                                </div>
                              )
                            })}
                          </div>
                          {ev.comment && (
                            <div style={{ padding: "0.75rem 1rem", background: "var(--surface-color)", borderRadius: "var(--radius-md)", border: "1px solid var(--border-color)", fontSize: "0.88rem", color: "var(--text-muted)" }}>
                              <strong style={{ color: "var(--text-main)" }}>Comentariu:</strong> {ev.comment}
                            </div>
                          )}
                        </td>
                      </tr>
                    )}
                  </>
                )
              })}
              {sorted.length === 0 && (
                <tr>
                  <td colSpan={9} style={{ padding: "3rem", textAlign: "center", color: "var(--text-muted)" }}>
                    {evaluations.length === 0 ? "Nicio evaluare găsită." : "Filtrarea nu returnează rezultate."}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
        </>
      )}
    </>
  )
}

/* ──────────────────────────────────────────────
 *  By-Entry aggregated view
 * ────────────────────────────────────────────── */

type EntryGroup = {
  entryId: string
  title: string
  subjectName: string
  city: string
  county: string
  student: string
  evaluations: Evaluation[]
  avgTotal: number
  evalCount: number
  allFinal: boolean
}

function ByEntryView({ evaluations }: { evaluations: Evaluation[] }) {
  const [search, setSearch] = useState("")
  const [expandedEntry, setExpandedEntry] = useState<string | null>(null)

  type EntrySortCol = "title" | "student" | "location" | "evalCount" | "avgTotal" | "status"
  const [sortCol, setSortCol] = useState<EntrySortCol>("avgTotal")
  const [sortAsc, setSortAsc] = useState(false)

  const handleSort = (col: EntrySortCol) => {
    if (sortCol === col) setSortAsc(!sortAsc)
    else { setSortCol(col); setSortAsc(col === "avgTotal" ? false : true) }
  }

  const EntrySortIndicator = ({ col }: { col: EntrySortCol }) => {
    if (sortCol !== col) return <span style={{ marginLeft: "0.25rem", opacity: 0.3 }}>⇅</span>
    return <span style={{ marginLeft: "0.25rem", color: "var(--primary)" }}>{sortAsc ? "↑" : "↓"}</span>
  }

  const groups = useMemo(() => {
    const map = new Map<string, EntryGroup>()
    for (const ev of evaluations) {
      let g = map.get(ev.entryId)
      if (!g) {
        g = {
          entryId: ev.entryId,
          title: ev.entry.title,
          subjectName: ev.entry.subjectName,
          city: ev.entry.city,
          county: ev.entry.county,
          student: ev.entry.user.name || "—",
          evaluations: [],
          avgTotal: 0,
          evalCount: 0,
          allFinal: true,
        }
        map.set(ev.entryId, g)
      }
      g.evaluations.push(ev)
    }
    for (const g of map.values()) {
      g.evalCount = g.evaluations.length
      g.avgTotal = Math.round(
        g.evaluations.reduce((acc, e) => acc + getTotal(e), 0) / g.evalCount
      )
      g.allFinal = g.evaluations.every(e => e.status === "FINAL")
    }
    return Array.from(map.values())
  }, [evaluations])

  const filtered = useMemo(() => {
    if (!search) return groups
    const term = search.toLowerCase()
    return groups.filter(g => {
      const fields = [g.title, g.subjectName, g.city, g.county, g.student]
      return fields.some(f => (f || "").toLowerCase().includes(term))
    })
  }, [groups, search])

  const sorted = useMemo(() => {
    return [...filtered].sort((a, b) => {
      let aVal: any, bVal: any
      switch (sortCol) {
        case "title": aVal = a.title; bVal = b.title; break
        case "student": aVal = a.student; bVal = b.student; break
        case "location": aVal = `${a.county} ${a.city}`; bVal = `${b.county} ${b.city}`; break
        case "evalCount": aVal = a.evalCount; bVal = b.evalCount; break
        case "avgTotal": aVal = a.avgTotal; bVal = b.avgTotal; break
        case "status": aVal = a.allFinal ? 1 : 0; bVal = b.allFinal ? 1 : 0; break
      }
      if (aVal === bVal) return 0
      if (aVal == null) return 1
      if (bVal == null) return -1
      if (typeof aVal === "string" && typeof bVal === "string") return sortAsc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
      return sortAsc ? (aVal < bVal ? -1 : 1) : (aVal > bVal ? -1 : 1)
    })
  }, [filtered, sortCol, sortAsc])

  const CRITERIA_LABELS = [
    { key: "relevance", label: "Relevanță", max: 15 },
    { key: "photoQuality", label: "Fotografie", max: 25 },
    { key: "originality", label: "Originalitate", max: 10 },
    { key: "documentation", label: "Documentare", max: 20 },
    { key: "gisIntegration", label: "GIS", max: 10 },
    { key: "presentation", label: "Prezentare", max: 10 },
    { key: "motivation", label: "Motivație", max: 10 },
  ]

  function scoreColor(pct: number): string {
    if (pct >= 0.75) return "var(--success)"
    if (pct >= 0.5) return "var(--primary)"
    if (pct >= 0.25) return "#d97706"
    return "var(--danger)"
  }

  return (
    <div style={{ background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", overflow: "hidden" }}>
      <div style={{ padding: "1.25rem 1.5rem", borderBottom: "1px solid var(--border-color)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "1rem" }}>
        <h2 style={{ fontSize: "1.15rem", fontWeight: 600, margin: 0 }}>
          Clasament per contribuție ({filtered.length})
        </h2>
        <input
          type="search"
          placeholder="Caută lucrare, elev, localitate…"
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{
            padding: "0.4rem 0.8rem",
            borderRadius: "var(--radius-sm)",
            border: "1px solid var(--border-color)",
            background: "var(--surface-hover)",
            color: "var(--text-main)",
            fontSize: "0.85rem",
            minWidth: "280px",
          }}
        />
      </div>

      <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", textAlign: "left" }}>
          <thead>
            <tr style={{ background: "var(--surface-hover)" }}>
              <th style={{ padding: "0.85rem 1.5rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase", width: "40px" }}>#</th>
              {[
                { key: "title", label: "Lucrare" },
                { key: "student", label: "Elev" },
                { key: "location", label: "Localitate" },
                { key: "evalCount", label: "Evaluatori", center: true },
                { key: "avgTotal", label: "Notă medie", center: true },
                { key: "status", label: "Status", center: true },
              ].map(h => (
                <th
                  key={h.key}
                  className="sortable-header"
                  onClick={() => handleSort(h.key as EntrySortCol)}
                  style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase", cursor: "pointer", userSelect: "none", whiteSpace: "nowrap", textAlign: (h as any).center ? "center" : "left" }}
                >
                  {h.label} <EntrySortIndicator col={h.key as EntrySortCol} />
                </th>
              ))}
              <th style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase", textAlign: "center" }}>Detalii</th>
            </tr>
          </thead>
          <tbody>
            {sorted.map((g, idx) => {
              const isExpanded = expandedEntry === g.entryId
              const pct = g.avgTotal / 100
              return (
                <>
                  <tr key={g.entryId} style={{ borderBottom: "1px solid var(--border-color)" }}>
                    <td style={{ padding: "0.85rem 1.5rem", fontWeight: 700, color: "var(--text-muted)", fontSize: "0.9rem" }}>{idx + 1}</td>
                    <td style={{ padding: "0.85rem 1rem" }}>
                      <div style={{ fontWeight: 500, color: "var(--text-main)", marginBottom: "0.15rem", maxWidth: "220px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{g.title}</div>
                      <div style={{ fontSize: "0.78rem", color: "var(--text-muted)" }}>{g.subjectName}</div>
                    </td>
                    <td style={{ padding: "0.85rem 1rem", fontSize: "0.88rem", color: "var(--text-muted)" }}>{g.student}</td>
                    <td style={{ padding: "0.85rem 1rem", fontSize: "0.85rem", color: "var(--text-muted)" }}>{g.city}, {g.county}</td>
                    <td style={{ padding: "0.85rem 1rem", textAlign: "center" }}>
                      <span style={{ fontWeight: 700, color: "var(--text-main)" }}>{g.evalCount}</span>
                    </td>
                    <td style={{ padding: "0.85rem 1rem", textAlign: "center" }}>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "0.5rem" }}>
                        <span style={{ fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "1.25rem", color: scoreColor(pct) }}>{g.avgTotal}</span>
                        <span style={{ color: "var(--text-muted)", fontSize: "0.82rem" }}>/100</span>
                      </div>
                      <div style={{ height: "3px", borderRadius: "2px", background: "var(--border-color)", marginTop: "0.3rem", width: "80px", margin: "0.3rem auto 0" }}>
                        <div style={{ height: "100%", borderRadius: "2px", width: `${pct * 100}%`, background: scoreColor(pct), transition: "width 0.3s" }} />
                      </div>
                    </td>
                    <td style={{ padding: "0.85rem 1rem", textAlign: "center" }}>
                      <span style={{
                        fontSize: "0.72rem", padding: "0.2rem 0.5rem", borderRadius: "999px",
                        background: g.allFinal ? "rgba(16, 185, 129, 0.1)" : "rgba(245, 158, 11, 0.1)",
                        color: g.allFinal ? "var(--success)" : "#d97706",
                        fontWeight: 600,
                      }}>
                        {g.allFinal ? "✓ Complet" : "În curs"}
                      </span>
                    </td>
                    <td style={{ padding: "0.85rem 1rem", textAlign: "center" }}>
                      <button
                        onClick={() => setExpandedEntry(isExpanded ? null : g.entryId)}
                        style={{ padding: "0.3rem 0.6rem", borderRadius: "var(--radius-sm)", background: "var(--primary-light)", color: "var(--primary)", border: "none", cursor: "pointer", fontSize: "0.8rem" }}
                      >
                        {isExpanded ? "▲ Ascunde" : "▼ Evaluări"}
                      </button>
                    </td>
                  </tr>

                  {isExpanded && (
                    <tr key={`${g.entryId}-detail`} style={{ borderBottom: "1px solid var(--border-color)", background: "var(--surface-hover)" }}>
                      <td colSpan={8} style={{ padding: "1rem 1.5rem" }}>
                        {/* Per-criterion averages */}
                        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(120px, 1fr))", gap: "0.5rem", marginBottom: "1rem" }}>
                          {CRITERIA_LABELS.map(c => {
                            const avg = Math.round(g.evaluations.reduce((acc, e) => acc + (e as any)[c.key], 0) / g.evalCount * 10) / 10
                            const cpct = avg / c.max
                            return (
                              <div key={c.key} style={{ background: "var(--surface-color)", padding: "0.6rem 0.75rem", borderRadius: "var(--radius-md)", border: "1px solid var(--border-color)", textAlign: "center" }}>
                                <div style={{ fontSize: "0.72rem", color: "var(--text-muted)", marginBottom: "0.2rem" }}>{c.label}</div>
                                <span style={{ fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "1.1rem", color: scoreColor(cpct) }}>{avg}</span>
                                <span style={{ fontSize: "0.72rem", color: "var(--text-muted)" }}>/{c.max}</span>
                              </div>
                            )
                          })}
                        </div>

                        {/* Individual evaluator rows */}
                        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.85rem" }}>
                          <thead>
                            <tr style={{ borderBottom: "1px solid var(--border-color)" }}>
                              <th style={{ padding: "0.5rem 0.75rem", textAlign: "left", color: "var(--text-muted)", fontWeight: 600, fontSize: "0.78rem" }}>Evaluator</th>
                              <th style={{ padding: "0.5rem 0.75rem", textAlign: "left", color: "var(--text-muted)", fontWeight: 600, fontSize: "0.78rem" }}>Comisie</th>
                              {CRITERIA_LABELS.map(c => (
                                <th key={c.key} style={{ padding: "0.5rem 0.4rem", textAlign: "center", color: "var(--text-muted)", fontWeight: 600, fontSize: "0.72rem" }}>{c.label}</th>
                              ))}
                              <th style={{ padding: "0.5rem 0.75rem", textAlign: "center", color: "var(--text-muted)", fontWeight: 600, fontSize: "0.78rem" }}>Total</th>
                              <th style={{ padding: "0.5rem 0.75rem", textAlign: "center", color: "var(--text-muted)", fontWeight: 600, fontSize: "0.78rem" }}>Status</th>
                            </tr>
                          </thead>
                          <tbody>
                            {g.evaluations.map(ev => {
                              const t = getTotal(ev)
                              return (
                                <tr key={ev.id} style={{ borderBottom: "1px solid var(--border-color)" }}>
                                  <td style={{ padding: "0.5rem 0.75rem", fontWeight: 500 }}>{ev.evaluator.name || ev.evaluator.email}</td>
                                  <td style={{ padding: "0.5rem 0.75rem" }}>
                                    <span style={{ fontSize: "0.72rem", padding: "0.15rem 0.4rem", borderRadius: "999px", background: "rgba(79, 70, 229, 0.08)", color: "var(--primary)", fontWeight: 700 }}>{getCommissionDisplayNameSync(ev.evaluator.commission)}</span>
                                  </td>
                                  {CRITERIA_LABELS.map(c => (
                                    <td key={c.key} style={{ padding: "0.5rem 0.4rem", textAlign: "center", fontWeight: 600, color: scoreColor((ev as any)[c.key] / c.max) }}>{(ev as any)[c.key]}</td>
                                  ))}
                                  <td style={{ padding: "0.5rem 0.75rem", textAlign: "center" }}>
                                    <span style={{ fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "1rem", color: scoreColor(t / 100) }}>{t}</span>
                                  </td>
                                  <td style={{ padding: "0.5rem 0.75rem", textAlign: "center" }}>
                                    <span style={{
                                      fontSize: "0.68rem", padding: "0.15rem 0.4rem", borderRadius: "999px",
                                      background: ev.status === "FINAL" ? "rgba(16, 185, 129, 0.1)" : "rgba(245, 158, 11, 0.1)",
                                      color: ev.status === "FINAL" ? "var(--success)" : "#d97706",
                                      fontWeight: 600,
                                    }}>
                                      {ev.status === "FINAL" ? "🔒" : "✎"}
                                    </span>
                                  </td>
                                </tr>
                              )
                            })}
                            {/* Average row */}
                            <tr style={{ background: "rgba(79, 70, 229, 0.04)" }}>
                              <td style={{ padding: "0.5rem 0.75rem", fontWeight: 700, color: "var(--primary)" }} colSpan={2}>MEDIE</td>
                              {CRITERIA_LABELS.map(c => {
                                const avg = Math.round(g.evaluations.reduce((acc, e) => acc + (e as any)[c.key], 0) / g.evalCount * 10) / 10
                                return <td key={c.key} style={{ padding: "0.5rem 0.4rem", textAlign: "center", fontWeight: 700, color: "var(--primary)" }}>{avg}</td>
                              })}
                              <td style={{ padding: "0.5rem 0.75rem", textAlign: "center" }}>
                                <span style={{ fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "1.1rem", color: "var(--primary)" }}>{g.avgTotal}</span>
                              </td>
                              <td />
                            </tr>
                          </tbody>
                        </table>
                      </td>
                    </tr>
                  )}
                </>
              )
            })}
            {filtered.length === 0 && (
              <tr>
                <td colSpan={8} style={{ padding: "3rem", textAlign: "center", color: "var(--text-muted)" }}>
                {groups.length === 0 ? "Nicio evaluare înregistrată." : "Niciun rezultat pentru căutare."}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}


function UnevaluatedView({ entries }: { entries: UnevaluatedEntry[] }) {
  const [search, setSearch] = useState("")

  const filtered = useMemo(() => {
    if (!search) return entries
    const term = search.toLowerCase()
    return entries.filter(e => {
      const fields = [e.title, e.subjectName, e.city, e.county, e.user.name, e.user.email, e.user.county]
      return fields.some(f => (f || "").toLowerCase().includes(term))
    })
  }, [entries, search])

  return (
    <div style={{ background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", overflow: "hidden" }}>
      <div style={{ padding: "1.25rem 1.5rem", borderBottom: "1px solid var(--border-color)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "1rem" }}>
        <h2 style={{ fontSize: "1.15rem", fontWeight: 600, margin: 0, display: "flex", alignItems: "center", gap: "0.5rem" }}>
          Contribuții neevaluate
          <span style={{ fontSize: "0.85rem", background: "rgba(239, 68, 68, 0.08)", color: "var(--danger)", padding: "0.2rem 0.6rem", borderRadius: "999px", fontWeight: 600 }}>
            {filtered.length}
          </span>
        </h2>
        <input
          type="search"
          placeholder="Caută obiectiv, elev, localitate…"
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{
            padding: "0.4rem 0.8rem",
            borderRadius: "var(--radius-sm)",
            border: "1px solid var(--border-color)",
            background: "var(--surface-hover)",
            color: "var(--text-main)",
            fontSize: "0.85rem",
            minWidth: "280px",
          }}
        />
      </div>

      <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", textAlign: "left" }}>
          <thead>
            <tr style={{ background: "var(--surface-hover)" }}>
              <th style={{ padding: "0.85rem 1.5rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase" }}>Lucrare</th>
              <th style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase" }}>Elev</th>
              <th style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase" }}>Localitate</th>
              <th style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase" }}>Județ elev</th>
              <th style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase" }}>Data trimiterii</th>
              <th style={{ padding: "0.85rem 1rem", fontSize: "0.8rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase" }}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(e => (
              <tr key={e.id} style={{ borderBottom: "1px solid var(--border-color)" }}>
                <td style={{ padding: "0.85rem 1.5rem" }}>
                  <div style={{ fontWeight: 500, color: "var(--text-main)", marginBottom: "0.15rem", maxWidth: "250px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.title}</div>
                  <div style={{ fontSize: "0.78rem", color: "var(--text-muted)" }}>{e.subjectName}</div>
                </td>
                <td style={{ padding: "0.85rem 1rem" }}>
                  <div style={{ fontWeight: 500, color: "var(--text-main)", marginBottom: "0.15rem" }}>{e.user.name || "—"}</div>
                  <div style={{ fontSize: "0.78rem", color: "var(--text-muted)" }}>{e.user.email}</div>
                </td>
                <td style={{ padding: "0.85rem 1rem", fontSize: "0.88rem", color: "var(--text-muted)" }}>
                  {e.city}, {e.county}
                </td>
                <td style={{ padding: "0.85rem 1rem", fontSize: "0.88rem", color: "var(--text-muted)" }}>
                  {e.user.county || "—"}
                </td>
                <td style={{ padding: "0.85rem 1rem", fontSize: "0.82rem", color: "var(--text-muted)", whiteSpace: "nowrap" }}>
                  {new Date(e.createdAt).toLocaleDateString("ro-RO")}
                </td>
                <td style={{ padding: "0.85rem 1rem" }}>
                  <span style={{
                    fontSize: "0.72rem", padding: "0.2rem 0.5rem", borderRadius: "999px",
                    background: "rgba(239, 68, 68, 0.08)", color: "var(--danger)", fontWeight: 600,
                  }}>
                    NEEVALUAT
                  </span>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr>
                <td colSpan={6} style={{ padding: "3rem", textAlign: "center", color: "var(--text-muted)" }}>
                  {entries.length === 0 ? "Toate contribuțiile au fost evaluate. 🎉" : "Niciun rezultat pentru căutare."}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
