"use client"

import { useState, useMemo } from "react"
import Link from "next/link"
import { PhotoCarousel } from "@/components/ui/PhotoCarousel"

type EvalScore = {
  relevance: number
  photoQuality: number
  originality: number
  documentation: number
  gisIntegration: number
  presentation: number
  motivation: number
  status: string
}

type EntryWithEval = {
  id: string
  title: string
  subjectName: string
  city: string
  county: string
  status: string
  createdAt: string | Date
  user: {
    name: string | null
    email: string | null
    class: string | null
    county: string | null
  }
  photos: { id: string; url: string; filename: string }[]
  evaluations: EvalScore[]
}

type EvalFilter = "ALL" | "NEEVALUAT" | "DRAFT" | "FINAL"

function getEvalTotal(ev: EvalScore): number {
  return ev.relevance + ev.photoQuality + ev.originality + ev.documentation + ev.gisIntegration + ev.presentation + ev.motivation
}

export function EvaluatorEntryList({ entries, frozen = false }: { entries: EntryWithEval[]; frozen?: boolean }) {
  const [searchTerm, setSearchTerm] = useState("")
  const [evalFilter, setEvalFilter] = useState<EvalFilter>("ALL")

  // Compute stats
  const stats = useMemo(() => {
    let total = entries.length
    let neevaluat = 0
    let draft = 0
    let finalized = 0
    for (const e of entries) {
      const ev = e.evaluations?.[0]
      if (!ev) neevaluat++
      else if (ev.status === "FINAL") finalized++
      else draft++
    }
    return { total, neevaluat, draft, finalized }
  }, [entries])

  const filteredEntries = useMemo(() => {
    return entries.filter(entry => {
      // 1. Evaluation status filter
      if (evalFilter !== "ALL") {
        const ev = entry.evaluations?.[0]
        if (evalFilter === "NEEVALUAT" && ev) return false
        if (evalFilter === "DRAFT" && (!ev || ev.status !== "DRAFT")) return false
        if (evalFilter === "FINAL" && (!ev || ev.status !== "FINAL")) return false
      }

      // 2. Free text search
      if (searchTerm) {
        const term = searchTerm.toLowerCase()
        const fields = [
          entry.title,
          entry.subjectName,
          entry.city,
          entry.county,
          entry.user.name,
          entry.user.email,
          entry.user.class,
          entry.user.county,
          new Date(entry.createdAt).toLocaleDateString("ro-RO"),
        ]
        if (!fields.some(f => (f || "").toLowerCase().includes(term))) {
          return false
        }
      }

      return true
    })
  }, [entries, evalFilter, searchTerm])

  const FILTER_PILLS: { key: EvalFilter; label: string; count: number }[] = [
    { key: "ALL", label: "Toate", count: stats.total },
    { key: "NEEVALUAT", label: "Neevaluate", count: stats.neevaluat },
    { key: "DRAFT", label: "Draft", count: stats.draft },
    { key: "FINAL", label: "Finalizate", count: stats.finalized },
  ]

  return (
    <>
      <style>{`
        .eval-card {
          background: var(--surface-color);
          border-radius: var(--radius-lg);
          overflow: hidden;
          border: 1px solid var(--border-color);
          box-shadow: var(--shadow-sm);
          transition: transform 0.15s ease, box-shadow 0.15s ease;
          cursor: pointer;
        }
        .eval-card:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0,0,0,0.12);
        }
      `}</style>

      {/* Filter bar */}
      <div style={{
        background: "var(--surface-color)",
        border: "1px solid var(--border-color)",
        borderRadius: "var(--radius-lg)",
        padding: "1rem 1.5rem",
        marginBottom: "1.5rem",
        display: "flex",
        flexWrap: "wrap",
        gap: "0.75rem",
        alignItems: "center",
      }}>
        {/* Status pills */}
        <div style={{ display: "flex", gap: "0.4rem", flexWrap: "wrap" }}>
          {FILTER_PILLS.map(fp => (
            <button
              key={fp.key}
              onClick={() => setEvalFilter(fp.key)}
              style={{
                padding: "0.4rem 0.85rem",
                borderRadius: "999px",
                border: "1px solid",
                background: evalFilter === fp.key ? "var(--primary)" : "var(--surface-color)",
                color: evalFilter === fp.key ? "white" : "var(--text-main)",
                borderColor: evalFilter === fp.key ? "var(--primary)" : "var(--border-color)",
                fontSize: "0.82rem",
                fontWeight: evalFilter === fp.key ? 600 : 400,
                cursor: "pointer",
                transition: "all 0.15s",
                display: "flex",
                alignItems: "center",
                gap: "0.35rem",
              }}
            >
              {fp.label}
              <span style={{
                fontSize: "0.72rem",
                background: evalFilter === fp.key ? "rgba(255,255,255,0.25)" : "var(--surface-hover)",
                padding: "0.1rem 0.4rem",
                borderRadius: "999px",
                fontWeight: 700,
              }}>
                {fp.count}
              </span>
            </button>
          ))}
        </div>

        {/* Search */}
        <div style={{ flex: 1, minWidth: "200px", marginLeft: "auto" }}>
          <input
            type="search"
            placeholder="Caută obiectiv, elev, localitate…"
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
            style={{
              width: "100%",
              padding: "0.5rem 0.85rem",
              borderRadius: "var(--radius-md)",
              border: "1px solid var(--border-color)",
              background: "var(--surface-hover)",
              color: "var(--text-main)",
              fontSize: "0.85rem",
            }}
          />
        </div>
      </div>

      {/* Results count */}
      <p style={{ color: "var(--text-muted)", fontSize: "0.85rem", marginBottom: "1rem" }}>
        {filteredEntries.length === entries.length
          ? `${filteredEntries.length} lucrări`
          : `${filteredEntries.length} din ${entries.length} lucrări`}
      </p>

      {/* Entries Grid */}
      {filteredEntries.length === 0 ? (
        <div style={{ textAlign: "center", padding: "4rem 2rem", background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px dashed var(--border-color)" }}>
          <div style={{ background: "var(--primary-light)", width: "64px", height: "64px", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 1.5rem", color: "var(--primary)" }}>
            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><path d="M8 12h8" /></svg>
          </div>
          <h3 style={{ fontSize: "1.25rem", marginBottom: "0.5rem" }}>
            {entries.length === 0 ? "Nu există lucrări pentru comisia ta" : "Niciun rezultat pentru filtrele selectate"}
          </h3>
          <p style={{ color: "var(--text-muted)", maxWidth: "400px", margin: "0 auto" }}>
            {entries.length === 0
              ? "Momentan nu sunt intrări trimise din județele alocate comisiei."
              : "Încearcă alte filtre sau termeni de căutare."}
          </p>
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: "1.5rem" }}>
          {filteredEntries.map((entry) => {
            const ev = entry.evaluations?.[0]
            const evalTotal = ev ? getEvalTotal(ev) : null

            return (
              <Link
                key={entry.id}
                href={`/evaluator/entry/${entry.id}`}
                style={{ textDecoration: "none", color: "inherit" }}
              >
                <div className="eval-card">
                  <PhotoCarousel
                    photos={entry.photos}
                    altText={entry.title}
                    height="200px"
                    borderRadius="0"
                  />
                  <div style={{ padding: "1.25rem" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "0.5rem" }}>
                      <h3 style={{ fontSize: "1.05rem", fontWeight: 600, display: "-webkit-box", WebkitLineClamp: 1, WebkitBoxOrient: "vertical", overflow: "hidden", flex: 1, marginRight: "0.5rem" }}>
                        {entry.title}
                      </h3>
                      {/* Eval status badge */}
                      {(() => {
                        if (!ev) {
                          return (
                            <span style={{
                              fontSize: "0.72rem", padding: "0.2rem 0.5rem", borderRadius: "999px",
                              background: "rgba(239, 68, 68, 0.08)", color: "var(--danger)", fontWeight: 600, flexShrink: 0,
                            }}>
                              NEEVALUAT
                            </span>
                          )
                        }
                        if (ev.status === "FINAL") {
                          return (
                            <span style={{
                              fontSize: "0.72rem", padding: "0.2rem 0.5rem", borderRadius: "999px",
                              background: "rgba(16, 185, 129, 0.1)", color: "var(--success)", fontWeight: 600, flexShrink: 0,
                            }}>
                              🔒 FINAL
                            </span>
                          )
                        }
                        return (
                          <span style={{
                            fontSize: "0.72rem", padding: "0.2rem 0.5rem", borderRadius: "999px",
                            background: "rgba(245, 158, 11, 0.1)", color: "#d97706", fontWeight: 600, flexShrink: 0,
                          }}>
                            ✎ DRAFT
                          </span>
                        )
                      })()}
                    </div>

                    <p style={{ color: "var(--text-muted)", fontSize: "0.88rem", marginBottom: "0.35rem", display: "flex", alignItems: "center", gap: "0.25rem" }}>
                      <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z" /><circle cx="12" cy="10" r="3" /></svg>
                      {entry.city}, {entry.county}
                    </p>

                    <p style={{ color: "var(--text-muted)", fontSize: "0.82rem", display: "flex", alignItems: "center", gap: "0.25rem" }}>
                      <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
                      {entry.user.name} {entry.user.class ? `(clasa a ${entry.user.class}-a)` : ""}
                    </p>

                    <div style={{ marginTop: "0.75rem", fontSize: "0.78rem", color: "var(--text-muted)", display: "flex", gap: "0.75rem", alignItems: "center" }}>
                      <span>📷 {entry.photos.length} foto</span>
                      <span>📅 {new Date(entry.createdAt).toLocaleDateString("ro-RO")}</span>
                      {evalTotal !== null && (
                        <span style={{
                          marginLeft: "auto",
                          padding: "0.15rem 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: 700,
                          fontSize: "0.8rem",
                        }}>
                          {evalTotal}/100
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </Link>
            )
          })}
        </div>
      )}
    </>
  )
}
