'use client'

import { X, FileText } from 'lucide-react'

export interface Att { id: string; name: string | null; image: boolean }

// Shared renderer: image attachments as thumbnails (tap → full size),
// other files (PDFs…) as named chips (tap → open/download). Pass onDelete
// to show the ✕ badges (edit contexts).
export function AttachmentRow({ atts, onDelete, className = '' }: { atts: Att[]; onDelete?: (id: string) => void; className?: string }) {
  if (!atts || atts.length === 0) return null
  return (
    <div className={`flex flex-wrap gap-1.5 ${className}`} onClick={e => e.stopPropagation()}>
      {atts.map(a => (
        <div key={a.id} className="relative">
          {a.image ? (
            <a href={`/api/image/${a.id}`} target="_blank" rel="noreferrer">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={`/api/image/${a.id}?thumb=1`} alt="" className="w-14 h-14 rounded-md object-cover border border-border" />
            </a>
          ) : (
            <a
              href={`/api/image/${a.id}`}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-1.5 text-xs rounded-lg border border-border bg-background px-2 py-1.5 text-muted-foreground hover:text-foreground max-w-44"
            >
              <FileText className="h-3.5 w-3.5 shrink-0" />
              <span className="truncate">{a.name || 'file'}</span>
            </a>
          )}
          {onDelete && (
            <button onClick={() => onDelete(a.id)} className="absolute -top-1.5 -right-1.5 bg-background border border-border rounded-full p-0.5" aria-label="Remove attachment">
              <X className="h-3 w-3" />
            </button>
          )}
        </div>
      ))}
    </div>
  )
}

export async function uploadAttachments(
  targetType: 'thought' | 'reminder' | 'checklist',
  targetId: string,
  files: File[],
): Promise<Att[]> {
  const fd = new FormData()
  fd.append('targetType', targetType)
  fd.append('targetId', targetId)
  files.forEach(f => fd.append('files', f))
  const res = await fetch('/api/attachments', { method: 'POST', body: fd })
  if (!res.ok) return []
  return ((await res.json()).attachments || []) as Att[]
}

export async function deleteAttachment(id: string): Promise<void> {
  await fetch(`/api/image/${id}`, { method: 'DELETE' })
}
