"use client"

import { useState, useCallback, useMemo } from "react"
import { useRouter } from "next/navigation"
import styles from "./EvaluationForm.module.css"

/* ──────────────────────────────────────────────
 *  Grila de evaluare — Anexa 4  (7 criterii)
 * ────────────────────────────────────────────── */

interface Band {
  min: number
  max: number
  label: string
  descriptor: string
  color: "low" | "medLow" | "medHigh" | "high"
}

interface Criterion {
  key: string
  number: number
  title: string
  maxScore: number
  bands: Band[]
}

const CRITERIA: Criterion[] = [
  {
    key: "relevance",
    number: 1,
    title: "Relevanța și încadrarea tematică",
    maxScore: 15,
    bands: [
      { min: 0, max: 4, label: "0–4", descriptor: "Subiect nerelevant", color: "low" },
      { min: 5, max: 8, label: "5–8", descriptor: "Relevanță limitată", color: "medLow" },
      { min: 9, max: 12, label: "9–12", descriptor: "Subiect adecvat, dar insuficient valorificat", color: "medHigh" },
      { min: 13, max: 15, label: "13–15", descriptor: "Subiect foarte bine ales, relevant pentru patrimoniu", color: "high" },
    ],
  },
  {
    key: "photoQuality",
    number: 2,
    title: "Calitatea fotografiei",
    maxScore: 25,
    bands: [
      { min: 0, max: 7, label: "0–7", descriptor: "Calitate slabă", color: "low" },
      { min: 8, max: 14, label: "8–14", descriptor: "Probleme de compoziție / claritate", color: "medLow" },
      { min: 15, max: 20, label: "15–20", descriptor: "Calitate bună, mici imperfecțiuni", color: "medHigh" },
      { min: 21, max: 25, label: "21–25", descriptor: "Imagine clară, compoziție foarte bună, încadrată corect, expresivă", color: "high" },
    ],
  },
  {
    key: "originality",
    number: 3,
    title: "Originalitate și perspectivă",
    maxScore: 10,
    bands: [
      { min: 0, max: 2, label: "0–2", descriptor: "Lipsă de originalitate", color: "low" },
      { min: 3, max: 5, label: "3–5", descriptor: "Abordare comună", color: "medLow" },
      { min: 6, max: 8, label: "6–8", descriptor: "Elemente de originalitate", color: "medHigh" },
      { min: 9, max: 10, label: "9–10", descriptor: "Abordare creativă, unghiuri originale", color: "high" },
    ],
  },
  {
    key: "documentation",
    number: 4,
    title: "Documentare (istorică, geografică, contextuală)",
    maxScore: 20,
    bands: [
      { min: 0, max: 5, label: "0–5", descriptor: "Informații eronate sau insuficiente", color: "low" },
      { min: 6, max: 11, label: "6–11", descriptor: "Documentare superficială", color: "medLow" },
      { min: 12, max: 16, label: "12–16", descriptor: "Informații corecte, dar incomplete", color: "medHigh" },
      { min: 17, max: 20, label: "17–20", descriptor: "Informații corecte, complete, bine structurate", color: "high" },
    ],
  },
  {
    key: "gisIntegration",
    number: 5,
    title: "Integrarea elementelor geografice (GIS)",
    maxScore: 10,
    bands: [
      { min: 0, max: 2, label: "0–2", descriptor: "Lipsă sau erori majore", color: "low" },
      { min: 3, max: 5, label: "3–5", descriptor: "Integrare limitată", color: "medLow" },
      { min: 6, max: 8, label: "6–8", descriptor: "Date corecte, dar parțial valorificate", color: "medHigh" },
      { min: 9, max: 10, label: "9–10", descriptor: "Coordonate corecte, localizare precisă, integrare clară", color: "high" },
    ],
  },
  {
    key: "presentation",
    number: 6,
    title: "Coerența și calitatea prezentării",
    maxScore: 10,
    bands: [
      { min: 0, max: 2, label: "0–2", descriptor: "Incoerență majoră", color: "low" },
      { min: 3, max: 5, label: "3–5", descriptor: "Structură slabă", color: "medLow" },
      { min: 6, max: 8, label: "6–8", descriptor: "Ușor neuniform, dar coerent", color: "medHigh" },
      { min: 9, max: 10, label: "9–10", descriptor: "Text clar, logic, bine redactat", color: "high" },
    ],
  },
  {
    key: "motivation",
    number: 7,
    title: "Motivația personală și valoarea educațională",
    maxScore: 10,
    bands: [
      { min: 0, max: 2, label: "0–2", descriptor: "Lipsă sau irelevantă", color: "low" },
      { min: 3, max: 5, label: "3–5", descriptor: "Formulare limitată", color: "medLow" },
      { min: 6, max: 8, label: "6–8", descriptor: "Motivație prezentă, dar superficială", color: "medHigh" },
      { min: 9, max: 10, label: "9–10", descriptor: "Reflecție personală relevantă și bine argumentată", color: "high" },
    ],
  },
]

/* ── Color helpers ── */
const BAND_CLASS: Record<string, string> = {
  low: styles.bandLow,
  medLow: styles.bandMedLow,
  medHigh: styles.bandMedHigh,
  high: styles.bandHigh,
}

const BAR_COLORS: Record<string, string> = {
  low: "#ef4444",
  medLow: "#f59e0b",
  medHigh: "#3b82f6",
  high: "#10b981",
}

function scoreColor(pct: number): string {
  if (pct >= 0.75) return "#10b981"
  if (pct >= 0.5) return "#3b82f6"
  if (pct >= 0.25) return "#f59e0b"
  return "#ef4444"
}

function bandForValue(criterion: Criterion, value: number): Band | null {
  return criterion.bands.find(b => value >= b.min && value <= b.max) ?? null
}

/* ── Props ── */
export interface EvaluationData {
  relevance: number
  photoQuality: number
  originality: number
  documentation: number
  gisIntegration: number
  presentation: number
  motivation: number
  comment: string
  status: "DRAFT" | "FINAL"
}

interface EvaluationFormProps {
  entryId: string
  initialData: EvaluationData | null
  nextEntryId?: string | null
  prevEntryId?: string | null
  frozen?: boolean
}

/* ──────────────────────────────────────────────
 *  Main component
 * ────────────────────────────────────────────── */

export function EvaluationForm({ entryId, initialData, nextEntryId, prevEntryId, frozen = false }: EvaluationFormProps) {
  const router = useRouter()
  const isLocked = initialData?.status === "FINAL" || frozen

  const defaultScores: Record<string, number> = {}
  for (const c of CRITERIA) {
    defaultScores[c.key] = initialData ? (initialData as any)[c.key] ?? 0 : 0
  }

  const [scores, setScores] = useState<Record<string, number>>(defaultScores)
  const [comment, setComment] = useState(initialData?.comment ?? "")
  const [saving, setSaving] = useState(false)
  const [showFinalConfirm, setShowFinalConfirm] = useState(false)
  const [toast, setToast] = useState<{ type: "success" | "error"; msg: string } | null>(null)

  // Track which criteria the evaluator has explicitly touched (interacted with).
  // If initialData exists, all criteria are considered already touched.
  const [touchedCriteria, setTouchedCriteria] = useState<Set<string>>(
    () => new Set(initialData ? CRITERIA.map(c => c.key) : [])
  )

  const total = useMemo(() => Object.values(scores).reduce((a, b) => a + b, 0), [scores])

  // Criteria that haven't been touched yet (evaluator hasn't interacted with them)
  const incompleteCriteria = useMemo(
    () => CRITERIA.filter(c => !touchedCriteria.has(c.key)),
    [touchedCriteria]
  )
  const canFinalize = incompleteCriteria.length === 0

  const setScore = useCallback((key: string, val: number) => {
    if (isLocked) return
    setScores(prev => ({ ...prev, [key]: val }))
    setTouchedCriteria(prev => {
      if (prev.has(key)) return prev
      const next = new Set(prev)
      next.add(key)
      return next
    })
  }, [isLocked])

  const handleBandClick = useCallback((criterion: Criterion, band: Band) => {
    if (isLocked) return
    // Jump to maximum of band, then fine-tune with slider
    setScore(criterion.key, band.max)
  }, [setScore, isLocked])

  const doSave = useCallback(async (targetStatus: "DRAFT" | "FINAL", navigateNext = false) => {
    setSaving(true)
    setToast(null)
    setShowFinalConfirm(false)
    try {
      const res = await fetch("/rovibe/api/evaluations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ entryId, ...scores, comment: comment || null, status: targetStatus }),
      })
      const data = await res.json()
      if (res.ok) {
        if (navigateNext && nextEntryId) {
          router.push(`/evaluator/entry/${nextEntryId}`)
          return
        }
        setToast({ type: "success", msg: data.message || "Evaluare salvată!" })
        if (targetStatus === "FINAL") {
          // Reload to show locked state from server
          window.location.reload()
        }
      } else {
        setToast({ type: "error", msg: data.message || "Eroare la salvare." })
      }
    } catch {
      setToast({ type: "error", msg: "Eroare de rețea." })
    } finally {
      setSaving(false)
    }
  }, [entryId, scores, comment, nextEntryId, router])

  const handleSaveDraft = useCallback(() => doSave("DRAFT"), [doSave])
  const handleSaveAndNext = useCallback(() => doSave("FINAL", true), [doSave])
  const handleFinalize = useCallback(() => setShowFinalConfirm(true), [])
  const handleConfirmFinalize = useCallback(() => doSave("FINAL"), [doSave])

  return (
    <div className={styles.wrapper}>
      {/* ── Sticky total header ── */}
      <div className={styles.stickyHeader}>
        <div>
          <div className={styles.stickyTitle}>
            Fișă de Evaluare — Anexa 4
            {frozen && (
              <span className={styles.lockedBadge} style={{ marginLeft: "0.75rem", background: "rgba(239, 68, 68, 0.1)", color: "var(--danger)" }}>
                🔒 Înghețat de admin
              </span>
            )}
            {!frozen && (initialData?.status === "FINAL") && (
              <span className={styles.lockedBadge} style={{ marginLeft: "0.75rem" }}>
                🔒 Evaluare finalizată
              </span>
            )}
            {initialData && !isLocked && (
              <span className={styles.draftBadge} style={{ marginLeft: "0.75rem" }}>
                ✎ Draft
              </span>
            )}
          </div>
        </div>
        <div className={styles.totalScore}>
          <span className={styles.totalValue} style={{ color: scoreColor(total / 100) }}>
            {total}
          </span>
          <span className={styles.totalMax}>/ 100</span>
        </div>
      </div>

      <div className={styles.totalBar}>
        <div
          className={styles.totalBarFill}
          style={{
            width: `${total}%`,
            background: `linear-gradient(90deg, ${scoreColor(total / 100)}, ${scoreColor(Math.min(1, total / 100 + 0.15))})`,
          }}
        />
      </div>

      {/* Frozen by admin message */}
      {frozen && (
        <div className={styles.lockedMessage} style={{ borderColor: "var(--danger)", background: "rgba(239, 68, 68, 0.06)" }}>
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--danger)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect width="18" height="11" x="3" y="11" rx="2" ry="2"/>
            <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
          </svg>
          <span style={{ color: "var(--danger)" }}>Evaluările tale au fost înghețate de administrator. Nu poți crea sau modifica evaluări.</span>
        </div>
      )}

      {/* Locked message */}
      {!frozen && (initialData?.status === "FINAL") && (
        <div className={styles.lockedMessage}>
          <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">
            <rect width="18" height="11" x="3" y="11" rx="2" ry="2"/>
            <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
          </svg>
          Această evaluare a fost finalizată și nu mai poate fi modificată.
        </div>
      )}

      {/* ── Criteria ── */}
      {CRITERIA.map(criterion => {
        const value = scores[criterion.key]
        const activeBand = bandForValue(criterion, value)
        const pct = value / criterion.maxScore

        return (
          <div key={criterion.key} className={`${styles.criterionCard} ${isLocked ? styles.criterionLocked : ""}`}>
            {/* Header */}
            <div className={styles.criterionHeader}>
              <div style={{ display: "flex", alignItems: "center" }}>
                <span className={styles.criterionNumber}>{criterion.number}</span>
                <span className={styles.criterionTitle}>{criterion.title}</span>
              </div>
              <span className={styles.criterionMax}>max {criterion.maxScore}p</span>
            </div>

            <div className={styles.criterionBody}>
              {/* Band pills */}
              <div className={styles.bandGroup}>
                {criterion.bands.map(band => {
                  const isSelected = activeBand === band
                  return (
                    <button
                      key={band.label}
                      type="button"
                      className={`${styles.bandPill} ${isSelected ? `${styles.bandPillSelected} ${BAND_CLASS[band.color]}` : ""}`}
                      onClick={() => handleBandClick(criterion, band)}
                      disabled={isLocked}
                    >
                      {band.label} p
                    </button>
                  )
                })}
              </div>

              {/* Descriptor table */}
              <table className={styles.descriptorTable}>
                <tbody>
                  {[...criterion.bands].reverse().map(band => {
                    const isActive = activeBand === band
                    return (
                      <tr
                        key={band.label}
                        className={isActive ? styles.descriptorActive : ""}
                        style={{ cursor: isLocked ? "default" : "pointer" }}
                        onClick={() => handleBandClick(criterion, band)}
                      >
                        <td className={styles.descriptorRange}>{band.label} p</td>
                        <td className={styles.descriptorText}>{band.descriptor}</td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>

              {/* Fine-tune slider */}
              <div className={styles.sliderRow}>
                <input
                  type="range"
                  className={styles.slider}
                  min={0}
                  max={criterion.maxScore}
                  value={value}
                  onChange={e => setScore(criterion.key, parseInt(e.target.value, 10))}
                  disabled={isLocked}
                  style={{
                    background: `linear-gradient(90deg, ${activeBand ? BAR_COLORS[activeBand.color] : "var(--border-color)"} ${pct * 100}%, var(--border-color) ${pct * 100}%)`,
                    opacity: isLocked ? 0.6 : 1,
                  }}
                />
                <span className={styles.sliderValue}>{value}</span>
              </div>

              {/* Mini bar */}
              <div className={styles.criterionBar} style={{ marginTop: "0.5rem" }}>
                <div
                  className={styles.criterionBarFill}
                  style={{
                    width: `${pct * 100}%`,
                    background: activeBand ? BAR_COLORS[activeBand.color] : "var(--border-color)",
                  }}
                />
              </div>
            </div>
          </div>
        )
      })}

      {/* ── Comment ── */}
      <div className={styles.commentSection}>
        <label className={styles.commentLabel}>
          💬 Comentariu general <span style={{ fontWeight: 400, color: "var(--text-muted)", fontSize: "0.85rem" }}>(opțional)</span>
        </label>
        <textarea
          className={styles.commentTextarea}
          placeholder="Observații, recomandări, aprecieri…"
          value={comment}
          onChange={e => setComment(e.target.value)}
          disabled={isLocked}
          style={isLocked ? { opacity: 0.6, cursor: "not-allowed" } : {}}
        />
      </div>

      {/* ── Submit area ── */}
      {!isLocked && (
        <div className={styles.submitArea}>
          {toast && (
            <div className={`${styles.toast} ${toast.type === "success" ? styles.toastSuccess : styles.toastError}`}>
              {toast.msg}
            </div>
          )}

          <div className={styles.submitRow}>
            <button
              type="button"
              className={styles.draftBtn}
              disabled={saving}
              onClick={handleSaveDraft}
            >
              {saving ? "Se salvează…" : "Salvează ca Draft"}
            </button>

            {nextEntryId && (
              <button
                type="button"
                className={styles.saveNextBtn}
                disabled={saving || !canFinalize}
                onClick={handleSaveAndNext}
                title={!canFinalize ? "Trebuie acordat punctaj la toate secțiunile" : "Finalizează evaluarea și treci la următoarea lucrare"}
              >
                {saving ? "Se salvează…" : "Finalizează & Înainte →"}
              </button>
            )}

            <button
              type="button"
              className={styles.finalizeBtn}
              disabled={saving || !canFinalize}
              onClick={handleFinalize}
              title={!canFinalize ? "Trebuie acordat punctaj la toate secțiunile" : ""}
            >
              Finalizează evaluarea
            </button>
          </div>

          {!canFinalize && (
            <div style={{
              width: "100%",
              padding: "0.6rem 1rem",
              borderRadius: "var(--radius-md)",
              background: "rgba(245, 158, 11, 0.08)",
              border: "1px solid rgba(245, 158, 11, 0.2)",
              color: "#d97706",
              fontSize: "0.82rem",
              lineHeight: 1.5,
            }}>
              ⚠ Pentru a finaliza, acordă punctaj la: {incompleteCriteria.map(c => `${c.number}. ${c.title}`).join(", ")}
            </div>
          )}
        </div>
      )}

      {/* ── Entry navigation ── */}
      {isLocked && (
        <div className={styles.entryNav}>
          {prevEntryId && (
            <button
              type="button"
              className={styles.navBtn}
              onClick={() => router.push(`/evaluator/entry/${prevEntryId}`)}
            >
              ← Lucrarea anterioară
            </button>
          )}
          {nextEntryId && (
            <button
              type="button"
              className={`${styles.navBtn} ${styles.navBtnPrimary}`}
              onClick={() => router.push(`/evaluator/entry/${nextEntryId}`)}
            >
              Lucrarea următoare →
            </button>
          )}
        </div>
      )}

      {/* ── Finalize confirmation modal ── */}
      {showFinalConfirm && (
        <div className={styles.modalOverlay} onClick={() => setShowFinalConfirm(false)}>
          <div className={styles.modalCard} onClick={e => e.stopPropagation()}>
            <div className={styles.modalIcon}>
              <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">
                <rect width="18" height="11" x="3" y="11" rx="2" ry="2"/>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
              </svg>
            </div>
            <h3 className={styles.modalTitle}>Finalizează evaluarea?</h3>
            <p className={styles.modalText}>
              Odată finalizată, evaluarea <strong>nu mai poate fi modificată</strong>.
              Punctajul total acordat: <strong style={{ color: scoreColor(total / 100) }}>{total}/100</strong>.
            </p>
            <div className={styles.modalActions}>
              <button
                type="button"
                className={styles.modalCancel}
                onClick={() => setShowFinalConfirm(false)}
              >
                Anulează
              </button>
              <button
                type="button"
                className={styles.modalConfirm}
                disabled={saving}
                onClick={handleConfirmFinalize}
              >
                {saving ? "Se finalizează…" : "Confirm — Finalizează"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
