'use client'

import { useState } from 'react'
import { ChevronDown, ChevronRight, Library } from 'lucide-react'
import type { EvidenceUnit } from '@/lib/sdk/advisor/contract'
import { resolveRegulation } from '@/lib/sdk/advisor/regulation-display'
import { EvidenceUnitCard } from './EvidenceUnitCard'
import { PaneHeader } from './PaneHeader'

interface Group {
  key: string
  label: string
  units: EvidenceUnit[]
}

function groupByFamily(units: EvidenceUnit[]): Group[] {
  const map = new Map<string, Group>()
  for (const u of units) {
    const d = resolveRegulation({ code: u.document, short: u.document })
    const g = map.get(d.familyKey) ?? { key: d.familyKey, label: d.familyLabel, units: [] }
    g.units.push(u)
    map.set(d.familyKey, g)
  }
  return [...map.values()].sort((a, b) => b.units.length - a.units.length)
}

function EvidenceGroup({ group, highlightedId }: { group: Group; highlightedId?: string }) {
  const [open, setOpen] = useState(group.units.length <= 3)
  return (
    <div className="rounded-lg border border-gray-200 bg-white">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="flex w-full items-center justify-between gap-2 px-2.5 py-2 text-left"
      >
        <span className="min-w-0 truncate text-xs font-semibold text-gray-900">{group.label}</span>
        <span className="flex flex-shrink-0 items-center gap-1 text-[11px] text-gray-500">
          {group.units.length} Treffer
          {open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
        </span>
      </button>
      {open && (
        <div className="space-y-1 border-t border-gray-100 px-2 py-2">
          {group.units.map((u) => (
            <EvidenceUnitCard key={u.evidence_id} unit={u} compact highlighted={u.evidence_id === highlightedId} />
          ))}
        </div>
      )}
    </div>
  )
}

/** Evidence pane — units grouped by document/regulation family, count + expandable. */
export function EvidencePane({
  evidence,
  highlightedId,
}: {
  evidence: EvidenceUnit[]
  highlightedId?: string
}) {
  const groups = groupByFamily(evidence)
  return (
    <section>
      <PaneHeader icon={<Library className="h-3.5 w-3.5 text-gray-500" />} title="Evidence" count={evidence.length} />
      {groups.length === 0 ? (
        <p className="px-1 text-[11px] text-gray-400">Keine strukturierte Evidence zu dieser Antwort.</p>
      ) : (
        <div className="space-y-1.5">
          {groups.map((g) => (
            <EvidenceGroup key={g.key} group={g} highlightedId={highlightedId} />
          ))}
        </div>
      )}
    </section>
  )
}
