<template>
  <div class="map-page">
    <div class="page-header">
      <h2>Shop Floor Map</h2>
      <router-link v-if="authStore.isAuthenticated" to="/map/editor" class="btn btn-primary">
        Edit Map
      </router-link>
    </div>

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

    <template v-else>
      <!-- Layer Toggles -->
      <div class="layer-toggles">
        <label v-for="t in assetTypes" :key="t.assettypeid" class="layer-toggle">
          <input
            type="checkbox"
            v-model="visibleTypes"
            :value="t.assettype"
            @change="updateMapLayers"
          />
          <span class="layer-icon">{{ getTypeIcon(t.assettype) }}</span>
          <span>{{ t.assettype }}</span>
          <span class="layer-count">({{ getTypeCount(t.assettype) }})</span>
        </label>
      </div>

      <ShopFloorMap
        :machines="filteredAssets"
        :machinetypes="[]"
        :businessunits="businessunits"
        :statuses="statuses"
        :assetTypeMode="true"
        :theme="currentTheme"
        @markerClick="handleMarkerClick"
      />
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ShopFloorMap from '../components/ShopFloorMap.vue'
import { assetsApi } from '../api'
import { currentTheme } from '../stores/theme'
import { useAuthStore } from '../stores/auth'

const router = useRouter()
const authStore = useAuthStore()
const loading = ref(true)
const assets = ref([])
const assetTypes = ref([])
const businessunits = ref([])
const statuses = ref([])
const visibleTypes = ref([])

const filteredAssets = computed(() => {
  if (visibleTypes.value.length === 0) return assets.value
  return assets.value.filter(a => visibleTypes.value.includes(a.assettype))
})

onMounted(async () => {
  try {
    const response = await assetsApi.getMap()
    const data = response.data.data || {}

    assets.value = data.assets || []
    assetTypes.value = data.filters?.assettypes || []
    businessunits.value = data.filters?.businessunits || []
    statuses.value = data.filters?.statuses || []

    // Default: show all types
    visibleTypes.value = assetTypes.value.map(t => t.assettype)
  } catch (error) {
    console.error('Failed to load map data:', error)
  } finally {
    loading.value = false
  }
})

function getTypeIcon(assettype) {
  const icons = {
    'equipment': '⚙',
    'computer': '💻',
    'printer': '🖨',
    'network_device': '🌐'
  }
  return icons[assettype] || '📦'
}

function getTypeCount(assettype) {
  return assets.value.filter(a => a.assettype === assettype).length
}

function updateMapLayers() {
  // Filter is reactive via computed property
}

function handleMarkerClick(asset) {
  // Route based on asset type
  const routeMap = {
    'equipment': '/machines',
    'computer': '/pcs',
    'printer': '/printers',
    'network_device': '/network'
  }

  const basePath = routeMap[asset.assettype] || '/machines'

  // For network devices, use the networkdeviceid from typedata
  if (asset.assettype === 'network_device' && asset.typedata?.networkdeviceid) {
    router.push(`/network/${asset.typedata.networkdeviceid}`)
  } else {
    // For machines (equipment, computer, printer), use machineid from typedata
    const id = asset.typedata?.machineid || asset.assetid
    router.push(`${basePath}/${id}`)
  }
}
</script>

<style scoped>
.map-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 2rem);
}

.map-page .page-header {
  flex-shrink: 0;
}

.layer-toggles {
  display: flex;
  gap: 1rem;
  padding: 0.75rem 1rem;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 8px;
  margin-bottom: 0.75rem;
  flex-wrap: wrap;
}

.layer-toggle {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  padding: 0.5rem 0.75rem;
  border-radius: 6px;
  transition: background 0.2s;
}

.layer-toggle:hover {
  background: var(--bg);
}

.layer-toggle input[type="checkbox"] {
  width: 1.125rem;
  height: 1.125rem;
}

.layer-icon {
  font-size: 1.25rem;
}

.layer-count {
  color: var(--text-light);
  font-size: 0.875rem;
}

.map-page :deep(.shopfloor-map) {
  flex: 1;
}
</style>
