<template>
  <div class="detail-page">
    <div class="page-header">
      <h2>Computer Details</h2>
      <div class="header-actions">
        <router-link :to="`/pcs/${$route.params.id}/edit`" class="btn btn-primary">Edit</router-link>
        <router-link to="/pcs" class="btn btn-secondary">Back to List</router-link>
      </div>
    </div>

    <div v-if="loading" class="loading">Loading...</div>

    <template v-else-if="computer">
      <!-- Hero Section -->
      <div class="hero-card">
        <div class="hero-content">
          <div class="hero-title">
            <h1>{{ computer.assetnumber }}</h1>
            <span v-if="isEnabled('fqdn', 'computer') && computer.computer?.hostname" class="hero-alias">{{ computer.computer.hostname }}</span>
          </div>
          <div class="hero-meta">
            <span class="badge badge-lg badge-info">Computer</span>
            <span class="badge badge-lg" :class="getStatusClass(computer.statusname)">
              {{ computer.statusname || 'Unknown' }}
            </span>
          </div>
          <div class="hero-details">
            <div class="hero-detail" v-if="computer.computer?.computertypename">
              <span class="hero-detail-label">Type</span>
              <span class="hero-detail-value">{{ computer.computer.computertypename }}</span>
            </div>
            <div class="hero-detail" v-if="computer.computer?.osname">
              <span class="hero-detail-label">OS</span>
              <span class="hero-detail-value">{{ computer.computer.osname }}</span>
            </div>
            <div class="hero-detail" v-if="computer.locationname">
              <span class="hero-detail-label">Location</span>
              <span class="hero-detail-value">{{ computer.locationname }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Main Content Grid -->
      <div class="content-grid">
        <!-- Left Column -->
        <div class="content-column">
          <!-- Identity Section -->
          <div class="section-card">
            <h3 class="section-title">Identity</h3>
            <div class="info-list">
              <div class="info-row">
                <span class="info-label">Asset Number</span>
                <span class="info-value">{{ computer.assetnumber }}</span>
              </div>
              <div class="info-row" v-if="computer.name">
                <span class="info-label">Name</span>
                <span class="info-value">{{ computer.name }}</span>
              </div>
              <div class="info-row" v-if="isEnabled('fqdn', 'computer') && computer.computer?.hostname">
                <span class="info-label">Hostname</span>
                <span class="info-value mono">{{ computer.computer.hostname }}</span>
              </div>
              <div class="info-row" v-if="computer.serialnumber">
                <span class="info-label">Serial Number</span>
                <span class="info-value mono">{{ computer.serialnumber }}</span>
              </div>
              <div class="info-row" v-if="isEnabled('gaugelabreference', 'computer') && computer.gaugelabreference">
                <span class="info-label">Gauge Lab Reference</span>
                <span class="info-value mono">{{ computer.gaugelabreference }}</span>
              </div>
              <div class="info-row" v-if="isEnabled('maintenancereference', 'computer') && computer.maintenancereference">
                <span class="info-label">Maintenance Reference</span>
                <span class="info-value mono">{{ computer.maintenancereference }}</span>
              </div>
            </div>
          </div>

          <!-- Hardware Section -->
          <div class="section-card">
            <h3 class="section-title">Hardware</h3>
            <div class="info-list">
              <div class="info-row">
                <span class="info-label">Computer Type</span>
                <span class="info-value">{{ computer.computer?.computertypename || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">Operating System</span>
                <span class="info-value">{{ computer.computer?.osname || '-' }}</span>
              </div>
            </div>
          </div>

          <!-- PC Status -->
          <div class="section-card">
            <h3 class="section-title">Status</h3>
            <div class="info-list">
              <div class="info-row" v-if="computer.computer?.loggedinuser">
                <span class="info-label">Logged In User</span>
                <span class="info-value">{{ computer.computer.loggedinuser }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">Features</span>
                <span class="info-value">
                  <span class="feature-tag" :class="{ active: computer.computer?.isvnc }">VNC</span>
                  <span class="feature-tag" :class="{ active: computer.computer?.iswinrm }">WinRM</span>
                  <span class="feature-tag" :class="{ active: computer.computer?.isshopfloor }">Shopfloor</span>
                </span>
              </div>
              <div class="info-row" v-if="computer.computer?.lastreporteddate">
                <span class="info-label">Last Reported</span>
                <span class="info-value">{{ formatDate(computer.computer.lastreporteddate) }}</span>
              </div>
              <div class="info-row" v-if="computer.computer?.lastboottime">
                <span class="info-label">Last Boot</span>
                <span class="info-value">{{ formatDate(computer.computer.lastboottime) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Right Column -->
        <div class="content-column">
          <!-- Location -->
          <div class="section-card">
            <h3 class="section-title">Location</h3>
            <div class="info-list">
              <div class="info-row">
                <span class="info-label">Location</span>
                <span class="info-value">
                  <LocationMapTooltip
                    v-if="computer.mapx != null && computer.mapy != null"
                    :left="computer.mapx"
                    :top="computer.mapy"
                    :machineName="computer.assetnumber"
                  >
                    <span class="location-link">{{ computer.locationname || 'On Map' }}</span>
                  </LocationMapTooltip>
                  <span v-else>{{ computer.locationname || '-' }}</span>
                </span>
              </div>
              <div class="info-row">
                <span class="info-label">Business Unit</span>
                <span class="info-value">{{ computer.businessunitname || '-' }}</span>
              </div>
            </div>
          </div>

          <!-- Controlled Equipment -->
          <div class="section-card" v-if="controlledEquipment.length > 0">
            <h3 class="section-title">Controlled Equipment</h3>
            <div class="equipment-list">
              <router-link
                v-for="item in controlledEquipment"
                :key="item.relationshipid"
                :to="`/machines/${item.pluginid || item.assetid}`"
                class="equipment-item"
              >
                <div class="equipment-info">
                  <span class="equipment-name">{{ item.assetnumber }}</span>
                  <span class="equipment-alias" v-if="item.name">{{ item.name }}</span>
                </div>
                <div class="equipment-meta">
                  <span class="category-tag">{{ item.assettypename }}</span>
                  <span class="connection-tag">{{ item.relationshipType }}</span>
                </div>
              </router-link>
            </div>
          </div>

          <!-- Installed Applications -->
          <div class="section-card" v-if="installedApps.length > 0">
            <h3 class="section-title">Installed Applications</h3>
            <div class="app-list">
              <router-link
                v-for="app in installedApps"
                :key="app.id"
                :to="`/applications/${app.application?.appid}`"
                class="app-item"
              >
                <div class="app-info">
                  <span class="app-name">{{ app.application?.appname }}</span>
                  <span class="app-version" v-if="app.version">v{{ app.version }}</span>
                </div>
                <div class="app-desc" v-if="app.application?.appdescription">
                  {{ app.application.appdescription }}
                </div>
              </router-link>
            </div>
          </div>

          <!-- Notes -->
          <div class="section-card" v-if="computer.notes">
            <h3 class="section-title">Notes</h3>
            <p class="notes-text">{{ computer.notes }}</p>
          </div>
        </div>
      </div>

      <!-- Audit Footer -->
      <div class="audit-footer">
        <span>Created {{ formatDate(computer.createddate) }}<template v-if="computer.createdby"> by {{ computer.createdby }}</template></span>
        <span>Modified {{ formatDate(computer.modifieddate) }}<template v-if="computer.modifiedby"> by {{ computer.modifiedby }}</template></span>
      </div>
    </template>

    <div v-else class="card">
      <p style="text-align: center; color: var(--text-light);">Computer not found</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { computersApi, applicationsApi, assetsApi } from '../../api'
import LocationMapTooltip from '../../components/LocationMapTooltip.vue'
import { useIdentifierFlags } from '../../composables/identifierSettings'

const route = useRoute()
const { isEnabled } = useIdentifierFlags()

const loading = ref(true)
const computer = ref(null)
const relationships = ref({ incoming: [], outgoing: [] })
const installedApps = ref([])

const controlledEquipment = computed(() => {
  // For computers, find related equipment in any "Controls" relationship
  const items = []

  // Check outgoing - computer controls equipment
  for (const rel of relationships.value.outgoing || []) {
    if (rel.targetasset?.assettypename === 'equipment' && rel.relationshiptypename === 'Controls') {
      items.push({
        ...rel.targetasset,
        relationshipid: rel.relationshipid,
        relationshipType: rel.relationshiptypename
      })
    }
  }

  // Also check incoming - legacy data may have equipment -> computer Controls relationships
  for (const rel of relationships.value.incoming || []) {
    if (rel.sourceasset?.assettypename === 'equipment' && rel.relationshiptypename === 'Controls') {
      items.push({
        ...rel.sourceasset,
        relationshipid: rel.relationshipid,
        relationshipType: rel.relationshiptypename
      })
    }
  }

  return items
})

onMounted(async () => {
  try {
    const response = await computersApi.get(route.params.id)
    computer.value = response.data.data

    // Load relationships using asset ID
    if (computer.value?.assetid) {
      try {
        const relResponse = await assetsApi.getRelationships(computer.value.assetid)
        relationships.value = relResponse.data.data || { incoming: [], outgoing: [] }
      } catch (e) {
        console.log('Relationships not available')
      }
    }

    // Load installed applications
    try {
      const appsResponse = await applicationsApi.getMachineApps(route.params.id)
      installedApps.value = appsResponse.data.data || []
    } catch (appError) {
      console.log('No installed apps data:', appError.message)
    }
  } catch (error) {
    console.error('Error loading computer:', error)
  } finally {
    loading.value = false
  }
})

function getStatusClass(status) {
  if (!status) return 'badge-info'
  const s = status.toLowerCase()
  if (s === 'in use' || s === 'active') return 'badge-success'
  if (s === 'in repair') return 'badge-warning'
  if (s === 'retired') return 'badge-danger'
  return 'badge-info'
}

function formatDate(dateStr) {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString()
}
</script>

<style scoped>
/* PC-specific styles - shared styles are in global style.css */

/* Installed Applications */
.app-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.app-item {
  display: block;
  padding: 1rem;
  background: var(--bg);
  border-radius: 8px;
  text-decoration: none;
  color: inherit;
  transition: background 0.15s;
}

.app-item:hover {
  background: var(--border);
  text-decoration: none;
}

.app-info {
  display: flex;
  align-items: baseline;
  gap: 0.75rem;
}

.app-name {
  font-weight: 500;
  font-size: 1.125rem;
  color: var(--text);
}

.app-version {
  font-size: 1rem;
  color: var(--text-light);
  font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;
}

.app-desc {
  margin-top: 0.375rem;
  font-size: 1rem;
  color: var(--text-light);
}

/* Equipment meta */
.equipment-meta {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.category-tag {
  padding: 0.3rem 0.625rem;
  font-size: 0.875rem;
  background: var(--primary);
  color: white;
  border-radius: 5px;
}

/* Network details */
.network-details {
  margin-top: 0.5rem;
  display: flex;
  gap: 1.25rem;
  font-size: 1rem;
  color: var(--text-light);
}
</style>
