'use client'
import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Pin, Trash2, Send, StickyNote } from 'lucide-react'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Button } from '@/components/ui/button'
import { cn, generateInitials } from '@/lib/utils'
import { useNotesStore } from '@/store/notesStore'
import { useAuthStore } from '@/store/authStore'
import { toast } from 'sonner'

const AVATAR_COLORS = ['bg-blue-600','bg-purple-600','bg-green-600','bg-orange-500','bg-pink-600']

function timeAgo(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime()
  const mins = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  if (mins < 1) return 'hace un momento'
  if (mins < 60) return `hace ${mins} min`
  if (hours < 24) return `hace ${hours}h`
  if (days === 1) return 'ayer'
  return `hace ${days} días`
}

function colorForAuthor(name: string) {
  const idx = name.charCodeAt(0) % AVATAR_COLORS.length
  return AVATAR_COLORS[idx]
}

export function NotesSection({ operationId }: { operationId: string }) {
  const { notes, addNote, deleteNote, togglePin } = useNotesStore()
  const { user } = useAuthStore()
  const [text, setText] = useState('')
  const [submitting, setSubmitting] = useState(false)

  const opNotes = notes
    .filter(n => n.operationId === operationId)
    .sort((a, b) => {
      if (a.pinned !== b.pinned) return a.pinned ? -1 : 1
      return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    })

  const handleSubmit = async () => {
    if (!text.trim()) return
    setSubmitting(true)
    await new Promise(r => setTimeout(r, 300))
    addNote(
      operationId,
      user?.id ?? 'anon',
      user?.name ?? 'Usuario',
      text.trim()
    )
    setText('')
    setSubmitting(false)
    toast.success('Nota agregada')
  }

  return (
    <div className="space-y-4">
      {/* Input */}
      <div className="bg-card border border-border rounded-xl p-4 space-y-3">
        <div className="flex gap-3">
          <Avatar className={`h-8 w-8 flex-shrink-0 ${colorForAuthor(user?.name ?? 'U')}`}>
            <AvatarFallback className="text-white text-xs bg-transparent">
              {generateInitials(user?.name ?? 'U')}
            </AvatarFallback>
          </Avatar>
          <textarea
            value={text}
            onChange={e => setText(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) handleSubmit()
            }}
            placeholder="Escribí una nota sobre esta operación... (Ctrl+Enter para enviar)"
            rows={3}
            className={cn(
              'flex-1 resize-none text-sm bg-muted/30 border border-border rounded-lg px-3 py-2',
              'placeholder:text-muted-foreground/50 text-foreground',
              'focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary/50',
              'transition-colors'
            )}
          />
        </div>
        <div className="flex justify-end">
          <Button
            size="sm"
            onClick={handleSubmit}
            disabled={!text.trim() || submitting}
            className="gap-2"
          >
            <Send size={13} />
            {submitting ? 'Guardando...' : 'Agregar nota'}
          </Button>
        </div>
      </div>

      {/* Notes list */}
      {opNotes.length === 0 ? (
        <div className="py-14 text-center">
          <StickyNote size={36} className="mx-auto mb-3 text-muted-foreground/20" />
          <p className="text-sm text-muted-foreground">Sin notas todavía</p>
          <p className="text-xs text-muted-foreground/60 mt-1">Las notas son visibles para todo el equipo</p>
        </div>
      ) : (
        <div className="space-y-3">
          <AnimatePresence initial={false}>
            {opNotes.map(note => (
              <motion.div
                key={note.id}
                initial={{ opacity: 0, y: -8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, x: 20 }}
                transition={{ duration: 0.2 }}
                className={cn(
                  'bg-card border rounded-xl p-4 group transition-colors',
                  note.pinned
                    ? 'border-primary/30 bg-primary/5'
                    : 'border-border hover:border-border/80'
                )}
              >
                <div className="flex items-start gap-3">
                  <Avatar className={`h-8 w-8 flex-shrink-0 ${colorForAuthor(note.authorName)}`}>
                    <AvatarFallback className="text-white text-xs bg-transparent">
                      {generateInitials(note.authorName)}
                    </AvatarFallback>
                  </Avatar>

                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1.5">
                      <span className="text-xs font-semibold text-foreground">{note.authorName}</span>
                      {note.pinned && (
                        <span className="flex items-center gap-0.5 text-[10px] font-medium text-primary bg-primary/10 px-1.5 py-0.5 rounded-full">
                          <Pin size={9} /> Fijada
                        </span>
                      )}
                      <span className="text-xs text-muted-foreground ml-auto">{timeAgo(note.createdAt)}</span>
                    </div>
                    <p className="text-sm text-foreground leading-relaxed whitespace-pre-wrap">{note.text}</p>
                  </div>

                  {/* Actions */}
                  <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
                    <button
                      onClick={() => togglePin(note.id)}
                      title={note.pinned ? 'Desfijar' : 'Fijar nota'}
                      className={cn(
                        'p-1.5 rounded-lg transition-colors',
                        note.pinned
                          ? 'text-primary bg-primary/10 hover:bg-primary/20'
                          : 'text-muted-foreground hover:text-primary hover:bg-primary/10'
                      )}
                    >
                      <Pin size={13} />
                    </button>
                    {(user?.id === note.authorId || user?.role === 'superusuario') && (
                      <button
                        onClick={() => {
                          deleteNote(note.id)
                          toast.success('Nota eliminada')
                        }}
                        title="Eliminar nota"
                        className="p-1.5 rounded-lg text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"
                      >
                        <Trash2 size={13} />
                      </button>
                    )}
                  </div>
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
        </div>
      )}
    </div>
  )
}
