/* tdd-guard:skip — client image-annotation UI, verified via gstack-smoke + Vercel-Preview (KAR-344 Phase 3) */
'use client'

import * as React from 'react'
import { Save, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { NoteCanvas } from '@/components/notes/note-canvas'
import { saveAttachmentAnnotations, deleteAttachment } from '@/app/notes/actions'
import { type NoteCanvasData } from '@/lib/notes/canvas'

export interface AttachmentItem {
  id: string
  url: string
  annotations: NoteCanvasData
}

export function NoteAttachmentAnnotator({ attachment }: { attachment: AttachmentItem }) {
  const [annotations, setAnnotations] = React.useState<NoteCanvasData>(attachment.annotations)
  const [pending, setPending] = React.useState(false)
  const [removed, setRemoved] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)
  const [saved, setSaved] = React.useState(false)

  if (removed) return null

  async function save() {
    setError(null)
    setSaved(false)
    setPending(true)
    const res = await saveAttachmentAnnotations(attachment.id, annotations)
    setPending(false)
    if (!res.ok) setError(res.error)
    else setSaved(true)
  }

  async function remove() {
    setError(null)
    setPending(true)
    const res = await deleteAttachment(attachment.id)
    setPending(false)
    if (!res.ok) setError(res.error)
    else setRemoved(true)
  }

  return (
    <div className="space-y-2 rounded-md border border-border p-3">
      <NoteCanvas
        value={annotations}
        onChange={(next) => {
          setAnnotations(next)
          setSaved(false)
        }}
        backgroundUrl={attachment.url}
        disabled={pending}
        heightClass="h-72"
      />
      <div className="flex items-center justify-between">
        <div className="text-xs">
          {error && <span className="text-destructive">{error}</span>}
          {saved && !error && <span className="text-primary">Annotation gespeichert.</span>}
        </div>
        <div className="flex gap-2">
          <Button type="button" variant="outline" size="lg" onClick={save} disabled={pending}>
            <Save size={16} />
            Annotation speichern
          </Button>
          <Button type="button" variant="destructive" size="lg" onClick={remove} disabled={pending}>
            <Trash2 size={16} />
            Löschen
          </Button>
        </div>
      </div>
    </div>
  )
}
