<script setup>
import { computed } from 'vue';
import { Card, Badge, Button } from '@/components/ui';
import { cn } from '@/lib/utils';
import DispositivoCard from './DispositivoCard.vue';
import SessionHistory from './SessionHistory.vue';

const props = defineProps({
  item: { type: Object, required: true },
  devicesById: { type: Object, default: () => ({}) },
  expandable: { type: Boolean, default: true },
  expanded: { type: Boolean, default: false }
});

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

const deviceList = computed(() => {
  const ids = props.item.dispositivos_utilizados || [];
  return ids.map(id => props.devicesById[id]).filter(Boolean);
});

function isConnected(id) {
  return Array.isArray(props.item.dispositivos_conectados) && props.item.dispositivos_conectados.includes(id);
}

const hasConnected = computed(() => Array.isArray(props.item.dispositivos_conectados) && props.item.dispositivos_conectados.length > 0);

const userInitial = computed(() => {
  const username = props.item.username || '';
  return username.charAt(0).toUpperCase() || '?';
});
</script>

<template>
  <div :class="cn(
    'relative transition-all duration-300',
    hasConnected && 'user-card-connected',
    item.disabled && 'opacity-60'
  )">
    <Card :class="cn(
      'p-5 transition-all duration-300 hover:shadow-lg',
      hasConnected && 'border-pink-400/30'
    )">
      <!-- Header -->
      <div class="flex items-center gap-3 mb-4 pb-4 border-b border-border">
        <div :class="cn(
          'size-9 flex items-center justify-center rounded-lg text-sm font-semibold',
          hasConnected ? 'bg-pink-400/12 text-pink-400' : 'bg-accent/10 text-accent'
        )">
          {{ userInitial }}
        </div>
        <h3 class="text-lg font-semibold tracking-tight">{{ item.username }}</h3>
      </div>

      <!-- Body -->
      <div class="flex flex-col gap-2.5 mb-4">
        <div class="flex justify-between items-center text-sm">
          <span class="text-muted font-medium lowercase tracking-wide">vlan</span>
          <span class="font-medium tabular-nums">{{ item.vlan }}</span>
        </div>
        <div class="flex justify-between items-center text-sm">
          <span class="text-muted font-medium lowercase tracking-wide">estado</span>
          <span class="font-medium">{{ item.disabled ? 'deshabilitado' : 'activo' }}</span>
        </div>
        <div v-if="hasConnected" class="flex justify-between items-center text-sm">
          <span class="text-muted font-medium lowercase tracking-wide">conexión</span>
          <span class="font-medium text-pink-400">conectado</span>
        </div>
        <div v-if="item.etiquetas && item.etiquetas.length" class="flex justify-between items-center text-sm">
          <span class="text-muted font-medium lowercase tracking-wide">etiquetas</span>
          <div class="flex gap-1.5 flex-wrap">
            <Badge v-for="tag in item.etiquetas" :key="tag" variant="secondary" class="text-[11px] py-0.5">
              {{ tag }}
            </Badge>
          </div>
        </div>
      </div>

      <!-- Actions -->
      <div class="flex gap-1.5 pt-4 border-t border-border">
        <Button variant="ghost" size="icon" @click="emit('edit', item)" title="Editar">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
          </svg>
        </Button>
        <Button variant="ghost" size="icon" @click="emit('disconnect', item)" title="Desconectar">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M18.36 6.64a9 9 0 1 1-12.73 0"></path>
            <line x1="12" y1="2" x2="12" y2="12"></line>
          </svg>
        </Button>
        <Button variant="ghost" size="icon" @click="emit('toggleDisable', item)" :title="item.disabled ? 'Habilitar' : 'Deshabilitar'">
          <svg v-if="item.disabled" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
            <circle cx="12" cy="12" r="3"></circle>
          </svg>
          <svg v-else width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
            <line x1="1" y1="1" x2="23" y2="23"></line>
          </svg>
        </Button>
        <Button variant="danger" size="icon" @click="emit('remove', item)" title="Eliminar">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="3 6 5 6 21 6"></polyline>
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
          </svg>
        </Button>
        <Button v-if="expandable" variant="ghost" size="icon" @click="emit('toggleExpand')" :title="expanded ? 'Contraer' : 'Expandir'">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" :class="expanded ? 'rotate-180' : ''" class="transition-transform">
            <polyline points="6 9 12 15 18 9"></polyline>
          </svg>
        </Button>
      </div>

      <!-- Devices -->
      <div v-if="expanded && deviceList.length" class="mt-4 pt-4 border-t border-border">
        <div class="grid gap-3">
          <DispositivoCard
            v-for="d in deviceList"
            :key="d.id"
            :device="d"
            :connected="isConnected(d.id)"
            simple
            @edit="emit('editDevice', d)"
          />
        </div>
      </div>

      <!-- Session History -->
      <div v-if="expanded" class="mt-4 pt-4 border-t border-border">
        <SessionHistory :username="item.username" :limit="5" />
      </div>
    </Card>
  </div>
</template>
