'use client'
import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Plus, X, UserCheck } from 'lucide-react'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { generateInitials } from '@/lib/utils'
import { toast } from 'sonner'

const AVAILABLE_USERS = [
  { id: 'horacio', name: 'Horacio Acosta', role: 'Titular' },
  { id: 'martin', name: 'Martín', role: 'Gestor' },
  { id: 'admin', name: 'Administración', role: 'Admin' },
  { id: 'sofia', name: 'Sofía', role: 'Gestora' },
  { id: 'lucas', name: 'Lucas', role: 'Gestor' },
]

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

interface Participant {
  id: string
  name: string
  role: string
}

interface ParticipantsPanelProps {
  initialParticipants?: Participant[]
}

export function ParticipantsPanel({ initialParticipants = [AVAILABLE_USERS[1]] }: ParticipantsPanelProps) {
  const [participants, setParticipants] = useState<Participant[]>(initialParticipants)
  const [showPicker, setShowPicker] = useState(false)

  const available = AVAILABLE_USERS.filter(u => !participants.find(p => p.id === u.id))

  const add = (user: Participant) => {
    setParticipants(prev => [...prev, user])
    setShowPicker(false)
    toast.success(`${user.name} agregado como participante`)
  }

  const remove = (id: string) => {
    setParticipants(prev => prev.filter(p => p.id !== id))
    toast.success('Participante removido')
  }

  return (
    <div className="bg-card border border-border rounded-xl p-5">
      <div className="flex items-center justify-between mb-4">
        <h4 className="text-sm font-semibold text-primary flex items-center gap-2">
          <UserCheck size={15} /> Participantes
        </h4>
        {available.length > 0 && (
          <button
            onClick={() => setShowPicker(!showPicker)}
            className="flex items-center gap-1 text-xs text-primary hover:underline"
          >
            <Plus size={13} /> Agregar
          </button>
        )}
      </div>

      {/* Lista de participantes */}
      <div className="space-y-2">
        <AnimatePresence>
          {participants.map((p, i) => (
            <motion.div
              key={p.id}
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -10 }}
              className="flex items-center gap-3 group"
            >
              <Avatar className={`h-8 w-8 flex-shrink-0 ${AVATAR_COLORS[i % AVATAR_COLORS.length]}`}>
                <AvatarFallback className="text-white text-xs bg-transparent">
                  {generateInitials(p.name)}
                </AvatarFallback>
              </Avatar>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-foreground">{p.name}</p>
                <p className="text-xs text-muted-foreground">{p.role}</p>
              </div>
              <button
                onClick={() => remove(p.id)}
                className="opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded hover:bg-destructive/10 text-destructive"
              >
                <X size={13} />
              </button>
            </motion.div>
          ))}
        </AnimatePresence>
      </div>

      {/* Picker para agregar */}
      <AnimatePresence>
        {showPicker && available.length > 0 && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="overflow-hidden"
          >
            <div className="mt-3 pt-3 border-t border-border space-y-1">
              <p className="text-xs text-muted-foreground mb-2">Seleccioná un usuario:</p>
              {available.map((u, i) => (
                <button
                  key={u.id}
                  onClick={() => add(u)}
                  className="w-full flex items-center gap-3 p-2 rounded-lg hover:bg-accent transition-colors text-left"
                >
                  <Avatar className={`h-7 w-7 ${AVATAR_COLORS[(participants.length + i) % AVATAR_COLORS.length]}`}>
                    <AvatarFallback className="text-white text-xs bg-transparent">
                      {generateInitials(u.name)}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <p className="text-sm font-medium text-foreground">{u.name}</p>
                    <p className="text-xs text-muted-foreground">{u.role}</p>
                  </div>
                </button>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {participants.length === 0 && (
        <p className="text-sm text-muted-foreground text-center py-2">Sin participantes asignados</p>
      )}
    </div>
  )
}
