'use client'

import { LegalTemplateResult, LicenseType, TemplateType, TEMPLATE_TYPE_LABELS } from '@/lib/sdk/types'
import LicenseBadge from './LicenseBadge'

export default function LibraryCard({
  template,
  expanded,
  onTogglePreview,
  onUse,
}: {
  template: LegalTemplateResult
  expanded: boolean
  onTogglePreview: () => void
  onUse: () => void
}) {
  const typeLabel = template.templateType
    ? (TEMPLATE_TYPE_LABELS[template.templateType as TemplateType] || template.templateType)
    : null
  const placeholderCount = template.placeholders?.length ?? 0

  return (
    <div className="bg-white rounded-xl border border-gray-200 overflow-hidden hover:border-purple-300 transition-colors">
      <div className="p-4">
        <div className="flex items-start justify-between gap-2 mb-2">
          <h3 className="font-medium text-gray-900 text-sm leading-snug">
            {template.documentTitle || 'Vorlage'}
          </h3>
          <span className="text-xs text-gray-400 uppercase shrink-0">{template.language}</span>
        </div>
        <div className="flex items-center gap-2 flex-wrap mb-3">
          {typeLabel && (
            <span className="text-xs text-purple-600 bg-purple-50 px-2 py-0.5 rounded">
              {typeLabel}
            </span>
          )}
          <LicenseBadge licenseId={template.licenseId as LicenseType} small />
          {placeholderCount > 0 && (
            <span className="text-xs text-gray-500">{placeholderCount} Platzh.</span>
          )}
        </div>
        <div className="flex gap-2">
          <button
            onClick={onTogglePreview}
            className="flex-1 text-xs px-3 py-1.5 border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-600 transition-colors"
          >
            {expanded ? 'Vorschau ▲' : 'Vorschau ▼'}
          </button>
          <button
            onClick={onUse}
            className="flex-1 text-xs px-3 py-1.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            Verwenden
          </button>
        </div>
      </div>

      {expanded && (
        <div className="border-t border-gray-100 bg-gray-50 p-4 max-h-[32rem] overflow-y-auto">
          <pre className="text-xs text-gray-600 whitespace-pre-wrap font-mono leading-relaxed">
            {template.text}
          </pre>
        </div>
      )}
    </div>
  )
}
