'use client'

/**
 * Entry detail pane — lightweight read-only inspector shown beside the
 * collection documents table (design's Entries split-pane, 400px). Surfaces
 * the entry's key fields, status, and timestamps; the primary action opens
 * the existing full editor route. Not an editor — editing stays in the
 * dedicated editor views.
 */
import { ExternalLink } from 'lucide-react'
import {
  InspectorPaneBody,
  InspectorPaneFooter,
  InspectorPaneHeader,
  InspectorPaneSection,
} from '../ui/InspectorPane.js'
import { StatusBadge, type StatusBadgeTone } from '../ui/StatusBadge.js'

interface FieldDef {
  type?: string
  label?: string
  hidden?: boolean
  options?: Array<{ label: string; value: string }>
}

const SKIPPED_FIELD_TYPES = new Set(['richText', 'blocks', 'json', 'media', 'relationship'])
const MAX_FIELDS = 8

function statusTone(status: string | undefined): StatusBadgeTone {
  switch (status?.toUpperCase()) {
    case 'PUBLISHED':
      return 'success'
    case 'SCHEDULED':
      return 'warning'
    case 'ARCHIVED':
      return 'muted'
    default:
      return 'neutral'
  }
}

function formatDateTime(value: unknown): string {
  if (typeof value !== 'string' || !value) return '—'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '—'
  return date.toLocaleDateString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  })
}

/** Human-readable display value for a scalar-ish field, or null to skip. */
function displayValue(raw: unknown, field: FieldDef): string | null {
  if (raw == null || raw === '') return ''
  if (typeof raw === 'boolean') return raw ? 'Yes' : 'No'
  if (typeof raw === 'number') return String(raw)
  if (typeof raw === 'string') {
    const opt = field.options?.find((o) => o.value === raw)
    return opt?.label ?? raw
  }
  if (Array.isArray(raw)) {
    const tags = raw
      .map((item) =>
        typeof item === 'string'
          ? item
          : item && typeof item === 'object'
            ? Object.values(item).find((v): v is string => typeof v === 'string')
            : undefined,
      )
      .filter((v): v is string => Boolean(v))
    if (tags.length > 0) return tags.join(', ')
    return `${raw.length} item${raw.length === 1 ? '' : 's'}`
  }
  return null
}

/** Key fields worth showing in the pane: labelled scalars from the config. */
function keyFields(
  fields: Record<string, FieldDef> | undefined,
  data: Record<string, unknown>,
): Array<{ name: string; label: string; value: string }> {
  if (!fields || typeof fields !== 'object') return []
  const out: Array<{ name: string; label: string; value: string }> = []
  for (const [name, field] of Object.entries(fields)) {
    if (!field || field.hidden) continue
    if (field.type && SKIPPED_FIELD_TYPES.has(field.type)) continue
    const value = displayValue(data[name], field)
    if (value === null) continue
    out.push({ name, label: field.label ?? name, value })
    if (out.length >= MAX_FIELDS) break
  }
  return out
}

export interface EntryDetailPaneProps {
  doc: Record<string, any>
  /** Collection definition from the CMS config (untyped upstream). */
  collection: any
  singularLabel: string
  onClose: () => void
  onOpenEditor: () => void
}

export function EntryDetailPane({
  doc,
  collection,
  singularLabel,
  onClose,
  onOpenEditor,
}: EntryDetailPaneProps) {
  const title = doc.title || doc.name || `#${doc.id}`
  const data = (doc.data ?? {}) as Record<string, unknown>
  const fields = keyFields(collection?.fields as Record<string, FieldDef> | undefined, data)

  return (
    <>
      <InspectorPaneHeader onClose={onClose} closeLabel={`Close ${singularLabel} details`}>
        <div className="truncate text-[13.5px] font-semibold text-[var(--txt)]">{title}</div>
        <div className="mt-1 flex items-center gap-2">
          <StatusBadge tone={statusTone(doc.status)}>{doc.status ?? 'DRAFT'}</StatusBadge>
          <span className="text-[11px] text-[var(--muted)]">{singularLabel}</span>
        </div>
      </InspectorPaneHeader>

      <InspectorPaneBody>
        <InspectorPaneSection title="Fields">
          {fields.length === 0 ? (
            <p className="text-[12px] text-[var(--muted)]">No previewable fields.</p>
          ) : (
            <dl>
              {fields.map((f) => (
                <div key={f.name} className="mb-2.5 last:mb-0">
                  <dt className="text-[10.5px] font-semibold tracking-[0.5px] text-[var(--muted)] uppercase">
                    {f.label}
                  </dt>
                  {f.value ? (
                    <dd className="mt-0.5 text-[12.5px] break-words text-[var(--txt)]">
                      {f.value}
                    </dd>
                  ) : (
                    <dd className="mt-0.5 text-[12.5px] text-[var(--muted)] italic">
                      Not provided
                    </dd>
                  )}
                </div>
              ))}
            </dl>
          )}
        </InspectorPaneSection>

        <InspectorPaneSection title="Record">
          <div className="flex items-center justify-between gap-3 py-1 text-[12px]">
            <span className="text-[var(--muted)]">Created</span>
            <span className="text-[var(--sub)]">{formatDateTime(doc.createdAt)}</span>
          </div>
          <div className="flex items-center justify-between gap-3 py-1 text-[12px]">
            <span className="text-[var(--muted)]">Updated</span>
            <span className="text-[var(--sub)]">{formatDateTime(doc.updatedAt)}</span>
          </div>
          <div className="flex items-center justify-between gap-3 py-1 text-[12px]">
            <span className="text-[var(--muted)]">ID</span>
            <span className="font-mono text-[11px] text-[var(--muted)]">{String(doc.id)}</span>
          </div>
        </InspectorPaneSection>
      </InspectorPaneBody>

      <InspectorPaneFooter>
        <button
          type="button"
          onClick={onOpenEditor}
          className="bg-primary text-primary-foreground flex w-full items-center justify-center gap-1.5 rounded-[7px] px-3 py-2 text-[13px] font-semibold transition-colors duration-[var(--motion-fast)] hover:opacity-90 focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none"
        >
          <ExternalLink size={14} aria-hidden />
          Open full editor
        </button>
      </InspectorPaneFooter>
    </>
  )
}
