'use client'

import * as React from 'react'
import { cn } from '../../lib/utils'

export type RecordFieldKind = 'text' | 'longtext' | 'url' | 'boolean' | 'json'

export interface RecordField {
  label: string
  value: string
  kind?: RecordFieldKind
}

export interface RecordDetailProps {
  fields: RecordField[]
  emptyMessage?: string
  className?: string
  /**
   * Show declared fields even when they have no value — the header stays with a
   * muted placeholder — instead of hiding them. Lets a reader tell that a field
   * (e.g. `content`) exists on the record but simply wasn't captured, rather than
   * wondering whether it's missing from the schema. Default false (hide empties).
   */
  showEmpty?: boolean
}

const URL_RE = /^https?:\/\//i

function hasValue(f: RecordField): boolean {
  return f.value != null && String(f.value).trim() !== ''
}

/**
 * Read-optimized view of a record's fields (startsim-768w.17.4). Renders short
 * fields as a compact label/value list (auto-linking urls), long-text fields as
 * readable, newline-preserving prose blocks (right for extracted article bodies),
 * and json as a scrollable code block. Generic: a consumer maps its own schema to
 * `fields` and this owns the layout, so every Foundry tenant's detail drawer reads
 * the same without duplicating the view.
 */
export function RecordDetail({ fields, emptyMessage = 'No details.', className, showEmpty = false }: RecordDetailProps) {
  const visible = showEmpty ? fields : fields.filter(hasValue)
  const shorts = visible.filter((f) => f.kind !== 'longtext' && f.kind !== 'json')
  const longs = visible.filter((f) => f.kind === 'longtext')
  const jsons = visible.filter((f) => f.kind === 'json')

  if (visible.length === 0) {
    return <p className={cn('text-sm text-muted-foreground', className)}>{emptyMessage}</p>
  }

  return (
    <div className={cn('space-y-4', className)}>
      {shorts.length > 0 && (
        <dl className="space-y-1.5">
          {shorts.map((f, i) => {
            const empty = !hasValue(f)
            const isUrl = !empty && (f.kind === 'url' || URL_RE.test(f.value))
            return (
              <div key={i} className="flex gap-2 text-sm">
                <dt className="w-28 shrink-0 capitalize text-muted-foreground">{f.label}</dt>
                <dd className="min-w-0 flex-1 break-words">
                  {empty ? (
                    <span className="text-muted-foreground">—</span>
                  ) : isUrl ? (
                    <a
                      href={f.value}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="break-all text-primary underline underline-offset-2 hover:no-underline"
                    >
                      {f.value}
                    </a>
                  ) : (
                    f.value
                  )}
                </dd>
              </div>
            )
          })}
        </dl>
      )}

      {longs.map((f, i) => (
        <section key={i} className="space-y-1.5">
          <h4 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
            {f.label}
          </h4>
          {hasValue(f) ? (
            <div className="whitespace-pre-wrap text-sm leading-relaxed text-foreground">
              {f.value}
            </div>
          ) : (
            <p className="text-sm italic text-muted-foreground">Not captured.</p>
          )}
        </section>
      ))}

      {jsons.map((f, i) => (
        <section key={i} className="space-y-1.5">
          <h4 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
            {f.label}
          </h4>
          {hasValue(f) ? (
            <pre className="overflow-x-auto rounded-md bg-muted p-3 text-xs leading-relaxed">
              {f.value}
            </pre>
          ) : (
            <p className="text-sm italic text-muted-foreground">Not captured.</p>
          )}
        </section>
      ))}
    </div>
  )
}
