<template>
  <div class="detail-page">
    <div class="page-header">
      <h2>Machine Details</h2>
      <div class="header-actions">
        <router-link :to="`/print/machine-badge/${machine?.machine?.machineid}`" class="btn btn-secondary" v-if="machine" target="_blank">
          Print Badge
        </router-link>
        <router-link :to="`/print/asset-label/machine/${machine?.machine?.machineid}`" class="btn btn-secondary" v-if="machine" target="_blank">
          Print Label
        </router-link>
        <router-link :to="`/machines/${machine?.machine?.machineid}/edit`" class="btn btn-primary" v-if="machine">
          Edit
        </router-link>
        <router-link to="/machines" class="btn btn-secondary">Back to List</router-link>
      </div>
    </div>

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

    <template v-else-if="machine">
      <!-- Dual-bay sibling banner: a Dualpath pair is one physical machine -->
      <div v-if="machine.dualpathpartner" class="dualpath-banner">
        Dual-bay machine - sibling bay:
        <router-link
          v-if="machine.dualpathpartner.machineid"
          :to="`/machines/${machine.dualpathpartner.machineid}`"
        >{{ machine.dualpathpartner.assetnumber }}</router-link>
        <span v-else>{{ machine.dualpathpartner.assetnumber }}</span>
      </div>

      <!-- Hero Section -->
      <div class="hero-card">
        <div class="hero-image" v-if="machine.machine?.imageurl">
          <img :src="machine.machine.imageurl" :alt="machine.machine.modelname || 'Model photo'" />
        </div>
        <div class="hero-content">
          <div class="hero-title">
            <h1>{{ machine.assetnumber }}</h1>
            <span v-if="machine.name" class="hero-alias">{{ machine.name }}</span>
          </div>
          <div class="hero-meta">
            <span class="badge badge-lg badge-primary">
              {{ machine.assettypename || 'Machine' }}
            </span>
            <span class="badge badge-lg" :class="getStatusClass(machine.statusname)">
              {{ machine.statusname || 'Unknown' }}
            </span>
            <span v-if="heroWarranty" class="badge badge-lg" :style="{ background: heroWarranty.statuscolor, color: '#fff' }"
                  :title="heroWarranty.enddate ? `Warranty ends ${warrantyDate(heroWarranty.enddate)}` : 'Warranty'">
              {{ heroWarranty.label }}<template v-if="heroWarranty.enddate"> - {{ warrantyDate(heroWarranty.enddate) }}</template>
            </span>
          </div>
          <div class="hero-details">
            <div class="hero-detail" v-if="machine.machine?.machinetypename">
              <span class="hero-detail-label">Type</span>
              <span class="hero-detail-value">{{ machine.machine.machinetypename }}</span>
            </div>
            <div class="hero-detail" v-if="machine.machine?.vendorname">
              <span class="hero-detail-label">Vendor</span>
              <span class="hero-detail-value">{{ machine.machine.vendorname }}</span>
            </div>
            <div class="hero-detail" v-if="machine.machine?.modelname">
              <span class="hero-detail-label">Model</span>
              <span class="hero-detail-value">{{ machine.machine.modelname }}</span>
            </div>
            <div class="hero-detail" v-if="machine.locationname">
              <span class="hero-detail-label">Location</span>
              <span class="hero-detail-value">{{ machine.locationname }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Canonical card order: Identity -> type-specific -> status -> Location & Organization -> domain -> Custom Fields -> Warranty -> Relationships -> Notes -> audit footer -->
      <!-- 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">{{ machine.assetnumber }}</span>
              </div>
              <div class="info-row" v-if="machine.name">
                <span class="info-label">Name</span>
                <span class="info-value">{{ machine.name }}</span>
              </div>
              <div class="info-row" v-if="isEnabled('gaugelabreference', 'machine') && machine.gaugelabreference">
                <span class="info-label">Gauge Lab Reference</span>
                <span class="info-value mono">{{ machine.gaugelabreference }}</span>
              </div>
              <div class="info-row" v-if="isEnabled('maintenancereference', 'machine') && machine.maintenancereference">
                <span class="info-label">Maintenance Reference</span>
                <span class="info-value mono">{{ machine.maintenancereference }}</span>
              </div>
              <div class="info-row" v-if="machine.serialnumber">
                <span class="info-label">Serial Number</span>
                <span class="info-value mono">{{ machine.serialnumber }}</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">Type</span>
                <span class="info-value">{{ machine.machine?.machinetypename || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">Vendor</span>
                <span class="info-value">{{ machine.machine?.vendorname || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">Model</span>
                <span class="info-value">{{ machine.machine?.modelname || '-' }}</span>
              </div>
            </div>
          </div>

          <!-- Controller Section (for CNC machines) -->
          <div class="section-card" v-if="machine.machine?.controllervendorname || machine.machine?.controllermodelname">
            <h3 class="section-title">Controller</h3>
            <div class="info-list">
              <div class="info-row">
                <span class="info-label">Vendor</span>
                <span class="info-value">{{ machine.machine?.controllervendorname || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">Model</span>
                <span class="info-value">{{ machine.machine?.controllermodelname || '-' }}</span>
              </div>
            </div>
          </div>

        </div>

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

          <!-- Machine Configuration -->
          <div class="section-card">
            <h3 class="section-title">Configuration</h3>
            <div class="info-list">
              <div class="info-row">
                <span class="info-label">Requires Manual Config</span>
                <span class="info-value">
                  <span class="feature-tag" :class="{ active: machine.machine?.requiresmanualconfig }">
                    {{ machine.machine?.requiresmanualconfig ? 'Yes' : 'No' }}
                  </span>
                </span>
              </div>
            </div>
          </div>

          <!-- Maintenance Section -->
          <div class="section-card" v-if="machine.machine?.lastmaintenancedate || machine.machine?.nextmaintenancedate">
            <h3 class="section-title">Maintenance</h3>
            <div class="info-list">
              <div class="info-row" v-if="machine.machine?.lastmaintenancedate">
                <span class="info-label">Last Maintenance</span>
                <span class="info-value">{{ formatDate(machine.machine.lastmaintenancedate) }}</span>
              </div>
              <div class="info-row" v-if="machine.machine?.nextmaintenancedate">
                <span class="info-label">Next Maintenance</span>
                <span class="info-value">{{ formatDate(machine.machine.nextmaintenancedate) }}</span>
              </div>
              <div class="info-row" v-if="machine.machine?.maintenanceintervaldays">
                <span class="info-label">Interval</span>
                <span class="info-value">{{ machine.machine.maintenanceintervaldays }} days</span>
              </div>
            </div>
          </div>

          <!-- Custom Fields -->
          <CustomFieldsSection :assetid="machine.assetid" />

          <!-- Plugin-contributed detail panels (ADR-010), incl. Warranty -->
          <PluginAssetPanels :assetid="machine.assetid" />

          <!-- All relationships (dualpath, controls, ...) -->
          <AssetRelationships v-if="machine.assetid" :assetid="machine.assetid" />

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

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

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

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { machinesApi } from '../../api'
import LocationMapTooltip from '../../components/LocationMapTooltip.vue'
import CustomFieldsSection from '../../components/CustomFieldsSection.vue'
import PluginAssetPanels from '../../components/PluginAssetPanels.vue'
import AssetRelationships from '../../components/AssetRelationships.vue'
import { useWarrantyBadge } from '../../composables/warrantyBadge'
import { useIdentifierFlags } from '../../composables/identifierSettings'

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

const loading = ref(true)
const machine = ref(null)
const { heroWarranty, warrantyDate } = useWarrantyBadge(() => machine.value?.assetid)

// relationships render via the shared AssetRelationships card

onMounted(async () => {
  try {
    const response = await machinesApi.get(route.params.id)
    machine.value = response.data.data
  } catch (error) {
    console.error('Error loading machine:', 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' || s === 'spare') return 'badge-warning'
  if (s === 'retired' || s === 'disposed') return 'badge-danger'
  return 'badge-info'
}

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

<style scoped>
.mono {
  font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;
}

.dualpath-banner {
  margin-bottom: 16px;
  padding: 10px 14px;
  border-radius: 6px;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-left: 4px solid var(--primary);
  color: var(--text);
  font-size: 0.9rem;
}

.dualpath-banner a {
  color: var(--link);
  font-weight: 600;
}

.feature-tag {
  display: inline-block;
  padding: 0.3rem 0.625rem;
  font-size: 0.875rem;
  border-radius: 5px;
  background: var(--bg);
  color: var(--text-light);
}

.feature-tag.active {
  background: #e3f2fd;
  color: #1976d2;
}

@media (prefers-color-scheme: dark) {
  .feature-tag.active {
    background: #1e3a5f;
    color: #60a5fa;
  }
}
</style>
