<script setup>
import { computed } from 'vue';
import { Card, Badge, Button } from '@/components/ui';
import UserCard from './UserCard.vue';

const props = defineProps({
  device: { type: Object, required: true },
  users: { type: Array, default: () => [] },
  devicesById: { type: Object, default: () => ({}) },
  simple: { type: Boolean, default: false },
  connected: { type: Boolean, default: false },
  expanded: { type: Boolean, default: false }
});

const emit = defineEmits(['edit', 'disconnect', 'toggleExpand']);

const connectedCount = computed(() => {
  if (!props.users || !props.users.length) return props.connected ? 1 : 0;
  const id = props.device.id;
  return props.users.filter(u => Array.isArray(u.dispositivos_conectados) && u.dispositivos_conectados.includes(id)).length;
});
</script>

<template>
  <Card class="p-3">
    <div class="flex flex-wrap items-center gap-2">
      <b>{{ device.nombre || device.mac }}</b>
      <Badge>MAC: {{ device.mac }}</Badge>
      <Badge variant="secondary">ID: {{ device.id }}</Badge>
      <Badge v-if="connectedCount > 0 || connected" variant="pink">
        Conectado
      </Badge>
      <span class="flex-1"></span>
      <Button size="sm" @click="emit('edit', device)">Editar</Button>
      <Button size="sm" variant="danger" @click="emit('disconnect', device)">Desconectar</Button>
      <Button v-if="!simple" size="sm" variant="ghost" @click="emit('toggleExpand')">
        {{ expanded ? 'Contraer' : 'Expandir' }}
      </Button>
    </div>

    <div v-if="device.nombre || device.descripcion" class="text-muted text-xs mt-1.5">
      <div v-if="device.nombre">Nombre: {{ device.nombre }}</div>
      <div v-if="device.descripcion">Descripción: {{ device.descripcion }}</div>
    </div>

    <div v-if="expanded && users && users.length" class="mt-2">
      <div class="grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-2.5">
        <UserCard
          v-for="u in users"
          :key="u.username"
          :item="u"
          :devicesById="devicesById"
          :expandable="false"
        />
      </div>
    </div>
  </Card>
</template>
