<script setup>
import { ref, onMounted, watch } from 'vue';
import { Card, Badge, Button } from '@/components/ui';
import { cn } from '@/lib/utils';

const props = defineProps({
  username: String,
  deviceId: Number,
  limit: { type: Number, default: 10 },
  showHeader: { type: Boolean, default: true }
});

const emit = defineEmits(['refresh']);

const sessions = ref([]);
const loading = ref(false);

async function fetchSessions() {
  loading.value = true;
  try {
    let url = '/api/sessions/history?limit=' + props.limit;
    if (props.username) url += '&username=' + encodeURIComponent(props.username);
    if (props.deviceId) url += '&dispositivo_id=' + props.deviceId;
    const res = await fetch(url);
    const data = await res.json();
    sessions.value = data.items || [];
  } catch (e) {
    console.error('Failed to fetch sessions:', e);
  } finally {
    loading.value = false;
  }
}

onMounted(fetchSessions);

watch(() => [props.username, props.deviceId], fetchSessions);

function formatDuration(seconds) {
  if (!seconds) return '-';
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  if (h > 0) return `${h}h ${m}m`;
  if (m > 0) return `${m}m ${s}s`;
  return `${s}s`;
}

function formatBytes(bytes) {
  if (!bytes) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  let i = 0;
  let b = bytes;
  while (b >= 1024 && i < units.length - 1) {
    b /= 1024;
    i++;
  }
  return b.toFixed(1) + ' ' + units[i];
}

function statusVariant(status) {
  return {
    active: 'pink',
    stopped: 'secondary',
    stale: 'warning'
  }[status] || 'secondary';
}

function formatTime(ts) {
  if (!ts) return '-';
  return new Date(ts).toLocaleString('es-HN', {
    day: '2-digit',
    month: 'short',
    hour: '2-digit',
    minute: '2-digit'
  });
}

function formatTimeShort(ts) {
  if (!ts) return '-';
  return new Date(ts).toLocaleString('es-HN', {
    hour: '2-digit',
    minute: '2-digit'
  });
}

defineExpose({ refresh: fetchSessions });
</script>

<template>
  <div class="space-y-2">
    <div v-if="showHeader" class="flex items-center justify-between mb-3">
      <span class="text-sm font-medium text-muted lowercase tracking-wide">historial de sesiones</span>
      <Button size="sm" variant="ghost" @click="fetchSessions" :disabled="loading">
        <svg :class="cn('size-3.5', loading && 'animate-spin')" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"></path>
          <path d="M21 3v5h-5"></path>
        </svg>
      </Button>
    </div>

    <div v-if="loading" class="text-muted text-sm py-4 text-center">Cargando historial...</div>
    <div v-else-if="!sessions.length" class="text-muted text-sm py-4 text-center">Sin sesiones registradas</div>

    <div v-else class="space-y-2">
      <div
        v-for="s in sessions"
        :key="s.id"
        :class="cn(
          'p-3 rounded-lg border border-border bg-card/50',
          s.status === 'active' && 'border-pink-400/30 bg-pink-400/5'
        )"
      >
        <div class="flex flex-wrap items-center gap-2">
          <Badge :variant="statusVariant(s.status)" class="text-[10px]">{{ s.status }}</Badge>
          <span v-if="!username" class="font-medium text-sm">{{ s.username }}</span>
          <span class="text-muted text-xs font-mono">{{ s.mac || s.calling_station_id || '-' }}</span>
          <span class="flex-1"></span>
          <span class="text-xs text-muted">{{ formatTime(s.started_at) }}</span>
        </div>

        <div v-if="s.status !== 'active'" class="text-xs text-muted mt-1.5">
          Fin: {{ formatTimeShort(s.ended_at) }}
          <span v-if="s.stop_reason" class="opacity-70 ml-1">({{ s.stop_reason }})</span>
        </div>

        <div class="flex flex-wrap gap-3 mt-2 text-xs text-muted">
          <span class="flex items-center gap-1" title="Duración">
            <svg class="size-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <polyline points="12 6 12 12 16 14"></polyline>
            </svg>
            {{ formatDuration(s.session_time) }}
          </span>
          <span class="flex items-center gap-1" title="Datos recibidos">
            <svg class="size-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <polyline points="7 13 12 18 17 13"></polyline>
              <polyline points="7 6 12 11 17 6"></polyline>
            </svg>
            {{ formatBytes(s.bytes_in) }}
          </span>
          <span class="flex items-center gap-1" title="Datos enviados">
            <svg class="size-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <polyline points="17 11 12 6 7 11"></polyline>
              <polyline points="17 18 12 13 7 18"></polyline>
            </svg>
            {{ formatBytes(s.bytes_out) }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>
