'use client'

import { useState } from 'react'
import { useDokumente, docLabel, downloadDoc, PublishedDoc } from './_hooks/useDokumente'

// Customer-facing "Dokumente": the finished, published legal documents the
// customer can read and download. Deliberately shows NO templates, NO drafts and
// NO generator — only what has been approved and published.

function fmtDate(iso: string | null): string {
  if (!iso) return '—'
  try {
    return new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: 'long', year: 'numeric' })
  } catch {
    return iso
  }
}

function DocCard({ doc }: { doc: PublishedDoc }) {
  const [open, setOpen] = useState(false)
  return (
    <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <span className="rounded bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 text-xs font-medium px-2 py-0.5">
              {docLabel(doc.type)}
            </span>
            <span className="text-xs text-gray-400">v{doc.version} · {doc.language?.toUpperCase()}</span>
          </div>
          <h3 className="mt-1.5 text-base font-semibold text-gray-900 dark:text-gray-100 truncate">
            {doc.title || docLabel(doc.type)}
          </h3>
          <p className="text-xs text-gray-500 mt-0.5">Veröffentlicht am {fmtDate(doc.published_at)}</p>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <button
            onClick={() => setOpen((v) => !v)}
            className="rounded border border-gray-300 dark:border-gray-600 text-sm px-3 py-1.5 text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            {open ? 'Schließen' : 'Ansehen'}
          </button>
          <button
            onClick={() => downloadDoc(doc)}
            className="rounded bg-indigo-600 hover:bg-indigo-700 text-white text-sm px-3 py-1.5"
          >
            Herunterladen
          </button>
        </div>
      </div>
      {open && (
        <article className="mt-4 max-h-[28rem] overflow-auto rounded-lg border border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40 p-4 text-sm leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap">
          {doc.content || 'Kein Inhalt hinterlegt.'}
        </article>
      )}
    </div>
  )
}

export default function DokumentePage() {
  const { docs, loading, error, reload } = useDokumente()

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Dokumente</h1>
        <p className="text-sm text-gray-600 dark:text-gray-300 mt-1 max-w-2xl">
          Ihre freigegebenen Rechtsdokumente — fertig zum Ansehen und Herunterladen. Hier erscheinen
          ausschließlich <span className="font-medium">veröffentlichte</span> Dokumente; Entwürfe und
          interne Vorlagen sind bewusst nicht enthalten.
        </p>
      </header>

      {loading && (
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-8 text-center text-sm text-gray-500">
          Lade Dokumente …
        </div>
      )}

      {error && !loading && (
        <div className="rounded-xl border border-amber-300 bg-amber-50 dark:bg-amber-900/20 text-amber-900 dark:text-amber-200 p-4 text-sm">
          Dokumente konnten gerade nicht geladen werden ({error}).{' '}
          <button onClick={reload} className="underline font-medium">Erneut versuchen</button>
        </div>
      )}

      {!loading && !error && docs.length === 0 && (
        <div className="rounded-xl border border-dashed border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 p-8 text-center">
          <p className="text-sm text-gray-700 dark:text-gray-200 font-medium">Noch keine veröffentlichten Dokumente</p>
          <p className="text-xs text-gray-500 mt-1 max-w-md mx-auto">
            Sobald ein Dokument intern und von Ihnen freigegeben und veröffentlicht wurde, erscheint es
            hier automatisch zum Download.
          </p>
        </div>
      )}

      {!loading && !error && docs.length > 0 && (
        <div className="grid gap-3">
          {docs.map((d) => <DocCard key={`${d.id}-${d.version}`} doc={d} />)}
        </div>
      )}
    </div>
  )
}
