"use client"

/**
 * NoteThread — fil de notes/commentaires professionnel partagé.
 * Utilisé côté tenant (agent) ET côté client (portail).
 *
 * - Bulles chronologiques avec avatar + nom + horodatage
 * - Édition inline (remplace la bulle par un textarea)
 * - Suppression avec confirmation
 * - Compositeur en bas (Ctrl+Enter pour envoyer)
 * - Auto-défilement vers le bas
 */

import React, { useEffect, useRef, useState } from "react"
import {
  Send, Pencil, Trash2, X, Check, Loader2, ChevronDown, AlertCircle,
} from "lucide-react"

// ── Types ──────────────────────────────────────────────────────────────────────

export type NoteItem = {
  id: number
  author_username?: string | null
  body: string
  created_at: string
  updated_at?: string | null
}

export type NoteThreadProps = {
  notes: NoteItem[]
  myUsername: string | null
  loading?: boolean
  submitting?: boolean
  error?: string | null
  onAdd: (body: string) => Promise<void>
  onEdit?: (noteId: number, body: string) => Promise<void>
  onDelete?: (noteId: number) => Promise<void>
  placeholder?: string
  emptyLabel?: string
  accentColor?: string
}

// ── Helpers ────────────────────────────────────────────────────────────────────

function timeAgo(iso: string): string {
  const diff = (Date.now() - new Date(iso).getTime()) / 1000
  if (diff < 60)     return "à l'instant"
  if (diff < 3600)   return `il y a ${Math.floor(diff / 60)} min`
  if (diff < 86400)  return `il y a ${Math.floor(diff / 3600)} h`
  return new Date(iso).toLocaleDateString("fr-FR", {
    day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit",
  })
}

/** Génère une teinte cohérente à partir du username */
function avatarColor(username: string | null | undefined): string {
  if (!username) return "#94a3b8"
  let hash = 0
  for (let i = 0; i < username.length; i++) hash = username.charCodeAt(i) + ((hash << 5) - hash)
  const palette = [
    "#1a3578", "#2655b0", "#1f7560", "#2d9073", "#3aaa87",
    "#7c3aed", "#b45309", "#0891b2", "#dc2626", "#059669",
  ]
  return palette[Math.abs(hash) % palette.length]
}

function initials(username: string | null | undefined): string {
  if (!username) return "?"
  const parts = username.split(/[._-\s]+/)
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase()
  return username.slice(0, 2).toUpperCase()
}

// ── Single note bubble ─────────────────────────────────────────────────────────

function NoteBubble({
  note, isMe, accentColor,
  onEdit, onDelete,
}: {
  note: NoteItem
  isMe: boolean
  accentColor: string
  onEdit?: (id: number, body: string) => Promise<void>
  onDelete?: (id: number) => void
}) {
  const [editing, setEditing] = useState(false)
  const [editBody, setEditBody] = useState(note.body)
  const [saving, setSaving] = useState(false)
  const [hover, setHover] = useState(false)
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const wasEdited = note.updated_at && note.updated_at !== note.created_at

  async function saveEdit() {
    const trimmed = editBody.trim()
    if (!trimmed || !onEdit) return
    setSaving(true)
    try {
      await onEdit(note.id, trimmed)
      setEditing(false)
    } finally {
      setSaving(false)
    }
  }

  function startEdit() {
    setEditBody(note.body)
    setEditing(true)
    setTimeout(() => textareaRef.current?.focus(), 50)
  }

  function cancelEdit() {
    setEditing(false)
    setEditBody(note.body)
  }

  const color = isMe ? accentColor : avatarColor(note.author_username)

  return (
    <div
      className="group flex items-start gap-3"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      {/* Avatar */}
      <div
        className="h-8 w-8 shrink-0 rounded-full flex items-center justify-center text-[11px] font-bold text-white mt-0.5"
        style={{ background: color }}
      >
        {initials(note.author_username)}
      </div>

      {/* Body */}
      <div className="flex-1 min-w-0">
        {/* Header */}
        <div className="flex items-center gap-2 mb-1.5">
          <span className="text-sm font-semibold text-slate-700">
            {note.author_username ? `@${note.author_username}` : "—"}
          </span>
          <span className="text-[11px] text-slate-400">{timeAgo(note.created_at)}</span>
          {wasEdited && (
            <span className="text-[10px] text-slate-300 italic">(modifié)</span>
          )}
        </div>

        {editing ? (
          /* Inline editor */
          <div className="space-y-2">
            <textarea
              ref={textareaRef}
              value={editBody}
              onChange={(e) => {
                setEditBody(e.target.value)
                e.target.style.height = "auto"
                e.target.style.height = e.target.scrollHeight + "px"
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); saveEdit() }
                if (e.key === "Escape") cancelEdit()
              }}
              disabled={saving}
              className="w-full resize-none rounded-2xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm text-slate-800 outline-none transition focus:border-teal-400 focus:ring-2 focus:ring-teal-400/20 min-h-[72px]"
            />
            <div className="flex items-center gap-2">
              <button
                onClick={saveEdit}
                disabled={saving || !editBody.trim()}
                className="inline-flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-xs font-semibold text-white transition disabled:opacity-50"
                style={{ background: accentColor }}
              >
                {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Check className="h-3.5 w-3.5" />}
                Enregistrer
              </button>
              <button
                onClick={cancelEdit}
                disabled={saving}
                className="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-xs text-slate-500 transition hover:bg-slate-50"
              >
                <X className="h-3.5 w-3.5" />
                Annuler
              </button>
            </div>
          </div>
        ) : (
          /* Note content */
          <div
            className="rounded-2xl px-4 py-2.5 text-sm leading-relaxed text-slate-800 whitespace-pre-wrap break-words"
            style={{
              background: isMe ? `${accentColor}12` : "#f8fafc",
              border: `1px solid ${isMe ? `${accentColor}25` : "#e2e8f0"}`,
            }}
          >
            {note.body}
          </div>
        )}
      </div>

      {/* Action buttons (hover, only mine, not editing) */}
      {isMe && !editing && (onEdit || onDelete) && (
        <div
          className="flex items-center gap-1 pt-0.5 transition-opacity duration-150"
          style={{ opacity: hover ? 1 : 0 }}
        >
          {onEdit && (
            <button
              onClick={startEdit}
              className="rounded-lg p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition"
              title="Modifier"
            >
              <Pencil className="h-3.5 w-3.5" />
            </button>
          )}
          {onDelete && (
            <button
              onClick={() => onDelete(note.id)}
              className="rounded-lg p-1.5 text-slate-400 hover:text-red-500 hover:bg-red-50 transition"
              title="Supprimer"
            >
              <Trash2 className="h-3.5 w-3.5" />
            </button>
          )}
        </div>
      )}
    </div>
  )
}

// ── Main component ─────────────────────────────────────────────────────────────

export function NoteThread({
  notes,
  myUsername,
  loading = false,
  submitting = false,
  error,
  onAdd,
  onEdit,
  onDelete,
  placeholder = "Ajouter une note… (Ctrl+Entrée pour envoyer)",
  emptyLabel = "Aucune note pour le moment. Soyez le premier à laisser un commentaire.",
  accentColor = "#1a3578",
}: NoteThreadProps) {
  const [body, setBody] = useState("")
  const bottomRef = useRef<HTMLDivElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const [showScroll, setShowScroll] = useState(false)

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [notes.length])

  async function submit() {
    const text = body.trim()
    if (!text || submitting) return
    setBody("")
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto"
    }
    await onAdd(text)
  }

  function handleDelete(noteId: number) {
    if (!onDelete) return
    if (!window.confirm("Supprimer cette note ?")) return
    onDelete(noteId)
  }

  return (
    <div className="flex flex-col h-full min-h-0 bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">

      {/* Header */}
      <div
        className="shrink-0 flex items-center justify-between px-5 py-3 border-b border-slate-100"
        style={{ background: `linear-gradient(90deg, ${accentColor}08 0%, transparent 100%)` }}
      >
        <div className="flex items-center gap-2">
          <div
            className="h-2 w-2 rounded-full"
            style={{ background: accentColor }}
          />
          <span className="text-sm font-semibold text-slate-700">Notes</span>
          {notes.length > 0 && (
            <span
              className="rounded-full px-1.5 py-0.5 text-[10px] font-bold text-white"
              style={{ background: accentColor }}
            >
              {notes.length}
            </span>
          )}
        </div>
      </div>

      {/* Notes list */}
      <div
        className="flex-1 overflow-y-auto px-5 py-4 space-y-5 scroll-smooth"
        onScroll={(e) => {
          const el = e.currentTarget
          setShowScroll(el.scrollHeight - el.scrollTop - el.clientHeight > 80)
        }}
      >
        {loading && (
          <div className="flex items-center justify-center py-10 text-slate-400">
            <Loader2 className="h-5 w-5 animate-spin mr-2" />
            Chargement…
          </div>
        )}

        {!loading && notes.length === 0 && (
          <div className="flex flex-col items-center justify-center py-12 text-center">
            <div className="h-12 w-12 rounded-2xl bg-slate-100 flex items-center justify-center mb-3">
              <Pencil className="h-5 w-5 text-slate-300" />
            </div>
            <p className="text-sm text-slate-400 max-w-xs">{emptyLabel}</p>
          </div>
        )}

        {notes.map((note) => (
          <NoteBubble
            key={note.id}
            note={note}
            isMe={!!myUsername && note.author_username === myUsername}
            accentColor={accentColor}
            onEdit={onEdit}
            onDelete={onDelete ? handleDelete : undefined}
          />
        ))}

        <div ref={bottomRef} />
      </div>

      {/* Scroll-to-bottom */}
      {showScroll && (
        <div className="relative">
          <button
            onClick={() => bottomRef.current?.scrollIntoView({ behavior: "smooth" })}
            className="absolute bottom-2 right-4 z-10 rounded-full border bg-white shadow-md p-1.5 hover:bg-slate-50 transition"
          >
            <ChevronDown className="h-4 w-4 text-slate-500" />
          </button>
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="mx-4 mb-2 flex items-center gap-2 rounded-xl border border-red-100 bg-red-50 px-3 py-2 text-xs text-red-700">
          <AlertCircle className="h-3.5 w-3.5 shrink-0" /> {error}
        </div>
      )}

      {/* Composer */}
      <div className="shrink-0 border-t border-slate-100 px-4 pb-4 pt-3">
        <div className="flex items-end gap-2">
          {/* Avatar of current user */}
          <div
            className="h-8 w-8 shrink-0 rounded-full flex items-center justify-center text-[11px] font-bold text-white mb-0.5"
            style={{ background: myUsername ? avatarColor(myUsername) : "#94a3b8" }}
          >
            {initials(myUsername)}
          </div>

          <div className="flex-1 flex items-end rounded-2xl border border-slate-200 bg-slate-50 focus-within:border-teal-400 focus-within:ring-2 focus-within:ring-teal-400/20 transition overflow-hidden px-3 py-2">
            <textarea
              ref={textareaRef}
              className="flex-1 resize-none bg-transparent text-sm outline-none max-h-32 min-h-[36px] leading-relaxed text-slate-800 placeholder:text-slate-400"
              placeholder={placeholder}
              rows={1}
              value={body}
              onChange={(e) => {
                setBody(e.target.value)
                e.target.style.height = "auto"
                e.target.style.height = e.target.scrollHeight + "px"
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
                  e.preventDefault()
                  submit()
                }
              }}
            />
          </div>

          <button
            onClick={submit}
            disabled={submitting || !body.trim()}
            className="shrink-0 h-10 w-10 rounded-2xl flex items-center justify-center text-white shadow-sm disabled:opacity-50 hover:opacity-90 transition"
            style={{ background: accentColor }}
            title="Envoyer (Ctrl+Entrée)"
          >
            {submitting
              ? <Loader2 className="h-4 w-4 animate-spin" />
              : <Send className="h-4 w-4" />
            }
          </button>
        </div>
        <p className="mt-1.5 text-[10px] text-slate-300 pl-10">Ctrl+Entrée pour envoyer · Entrée pour une nouvelle ligne</p>
      </div>
    </div>
  )
}
