/**
 * Single fact card in the What-we-know section.
 *
 * Layout per FLOWPILOT-MIGRATION.md Section 3.1:
 *   [✓] <fact text>
 *       <provenance line: 'from question · rules out tenant/license'>
 *
 * Editability: the server marks `editable=false` for `question` and
 * `diagnostic_check` facts (those are edited at the source item, not here).
 * Manual notes and AI-synthesized facts are editable inline.
 *
 * Delete is allowed for all source types — even read-only facts may be
 * removed when the underlying question or check turned out to be wrong.
 */
import { useState } from 'react'
import { Check, Pencil, Trash2, X } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { SessionFact, SessionFactSourceType } from '@/api/sessionFacts'

interface WhatWeKnowItemProps {
  fact: SessionFact
  onSave: (text: string, summary: string | null) => Promise<void> | void
  onDelete: () => Promise<void> | void
}

const SOURCE_LABEL: Record<SessionFactSourceType, string> = {
  question: 'from question',
  diagnostic_check: 'from check',
  user_note: 'manual note',
  ai_synthesis: 'synthesized',
}

export function WhatWeKnowItem({ fact, onSave, onDelete }: WhatWeKnowItemProps) {
  const [editing, setEditing] = useState(false)
  const [draftText, setDraftText] = useState(fact.text)
  const [draftSummary, setDraftSummary] = useState(fact.source_summary ?? '')
  const [busy, setBusy] = useState(false)

  const handleSave = async () => {
    if (!draftText.trim()) return
    setBusy(true)
    try {
      await onSave(draftText.trim(), draftSummary.trim() || null)
      setEditing(false)
    } finally {
      setBusy(false)
    }
  }

  const handleCancel = () => {
    setDraftText(fact.text)
    setDraftSummary(fact.source_summary ?? '')
    setEditing(false)
  }

  const handleDelete = async () => {
    setBusy(true)
    try {
      await onDelete()
    } finally {
      setBusy(false)
    }
  }

  const provenanceLabel = SOURCE_LABEL[fact.source_type]

  if (editing) {
    return (
      <div className="rounded-lg border border-default bg-card p-3 mb-2">
        <textarea
          autoFocus
          value={draftText}
          onChange={(e) => setDraftText(e.target.value)}
          className="w-full rounded-md border border-default bg-input px-2.5 py-1.5 text-[0.8125rem] text-heading resize-y min-h-[44px] max-h-[140px] focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/30"
          rows={2}
        />
        <input
          type="text"
          value={draftSummary}
          onChange={(e) => setDraftSummary(e.target.value)}
          placeholder="Short label (e.g. 'rules out tenant/license')"
          className="mt-1.5 w-full rounded-md border border-default bg-input px-2.5 py-1 text-[0.75rem] text-heading placeholder:text-muted-foreground focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/30"
        />
        <div className="mt-1.5 flex items-center gap-2">
          <button
            onClick={handleSave}
            disabled={busy || !draftText.trim()}
            className="flex items-center gap-1 rounded-md bg-accent px-2.5 py-1 text-[0.75rem] font-medium text-white disabled:opacity-40 hover:bg-accent-hover transition-colors"
          >
            <Check size={11} /> Save
          </button>
          <button
            onClick={handleCancel}
            disabled={busy}
            className="text-[0.75rem] text-muted-foreground hover:text-heading"
          >
            Cancel
          </button>
        </div>
      </div>
    )
  }

  return (
    <div
      className={cn(
        'group rounded-lg border-l-[3px] border-l-success border border-success/25 bg-success-dim/20 p-3 mb-2',
        busy && 'opacity-60',
      )}
    >
      <div className="flex items-start gap-2">
        <div className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border border-dashed border-success">
          <Check size={9} className="text-success" />
        </div>
        <div className="min-w-0 flex-1">
          <div className="text-[0.8125rem] text-heading leading-relaxed">{fact.text}</div>
          <div className="mt-1 text-[0.6875rem] text-muted-foreground">
            <span>{provenanceLabel}</span>
            {fact.source_summary && (
              <>
                <span className="mx-1">·</span>
                <span className="italic">{fact.source_summary}</span>
              </>
            )}
          </div>
        </div>
        <div className="flex shrink-0 items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          {fact.editable && (
            <button
              onClick={() => setEditing(true)}
              disabled={busy}
              className="p-1 rounded text-muted-foreground hover:text-heading hover:bg-elevated/40 transition-colors"
              title="Edit fact"
            >
              <Pencil size={11} />
            </button>
          )}
          <button
            onClick={handleDelete}
            disabled={busy}
            className="p-1 rounded text-muted-foreground hover:text-danger hover:bg-elevated/40 transition-colors"
            title="Remove fact"
          >
            {busy ? <X size={11} /> : <Trash2 size={11} />}
          </button>
        </div>
      </div>
    </div>
  )
}

export default WhatWeKnowItem
