<template>
  <div class="map-editor">
    <div class="page-header">
      <h2>Map Editor</h2>
      <div class="header-actions">
        <router-link to="/map" class="btn btn-secondary">Back to Map</router-link>
      </div>
    </div>

    <div class="editor-layout">
      <!-- Asset List Panel -->
      <div class="asset-panel">
        <div class="panel-header">
          <h3>Assets</h3>
          <select v-model="filterType" class="form-control">
            <option value="">All Types</option>
            <option value="machine">Machines</option>
            <option value="computer">Computers</option>
            <option value="printer">Printers</option>
            <option value="network_device">Network Devices</option>
          </select>
        </div>

        <div class="asset-filter">
          <label class="filter-checkbox">
            <input type="checkbox" v-model="showUnplacedOnly" />
            Show unplaced only
          </label>
        </div>

        <div class="asset-list">
          <div
            v-for="asset in filteredAssets"
            :key="asset.assetid"
            class="asset-item"
            :class="{
              selected: selectedAsset?.assetid === asset.assetid,
              placed: asset.mapx && asset.mapy,
              unplaced: !asset.mapx || !asset.mapy
            }"
            @click="selectAsset(asset)"
          >
            <span class="asset-icon"><component :is="getTypeIcon(asset.assettype)" :size="16" /></span>
            <div class="asset-info">
              <div class="asset-name">{{ asset.name || asset.assetnumber }}</div>
              <div class="asset-meta">
                <span class="badge badge-sm">{{ asset.assettype }}</span>
                <span v-if="asset.mapx && asset.mapy" class="placed-indicator" title="Placed on map"><MapPin :size="12" /></span>
              </div>
            </div>
          </div>

          <div v-if="filteredAssets.length === 0" class="empty">
            No assets found.
          </div>
        </div>
      </div>

      <!-- Map Panel -->
      <div class="map-panel">
        <div class="map-toolbar" v-if="selectedAsset">
          <span class="selected-info">
            <strong>Selected:</strong> {{ selectedAsset.name || selectedAsset.assetnumber }}
          </span>
          <span class="position-info" v-if="pickedPosition">
            Position: ({{ Math.round(pickedPosition.left) }}, {{ Math.round(pickedPosition.top) }})
          </span>
          <div class="toolbar-actions">
            <button
              class="btn btn-primary"
              :disabled="!pickedPosition"
              @click="savePosition"
            >
              Save Position
            </button>
            <button
              class="btn btn-danger"
              v-if="selectedAsset.mapx && selectedAsset.mapy"
              @click="clearPosition"
            >
              Remove from Map
            </button>
            <button class="btn btn-secondary" @click="cancelEdit">Cancel</button>
          </div>
        </div>

        <div class="map-toolbar" v-else>
          <span class="instruction">Select an asset from the list to place it on the map</span>
        </div>

        <ShopFloorMap
          ref="mapRef"
          :machines="placedAssets"
          :assetTypeMode="true"
          :theme="currentTheme"
          :pickerMode="!!selectedAsset"
          :initialPosition="selectedAsset ? { left: selectedAsset.mapx, top: selectedAsset.mapy } : null"
          @positionPicked="handlePositionPicked"
          @markerClick="handleMarkerClick"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Cog, Monitor, Printer, Globe, Package, MapPin } from 'lucide-vue-next'
import ShopFloorMap from '../components/ShopFloorMap.vue'
import { assetsApi } from '../api'
import { currentTheme } from '../stores/theme'
import { useToast } from '../composables/toast'
const toast = useToast()

const assets = ref([])
const loading = ref(true)
const selectedAsset = ref(null)
const pickedPosition = ref(null)
const filterType = ref('')
const showUnplacedOnly = ref(false)

const filteredAssets = computed(() => {
  let result = assets.value

  if (filterType.value) {
    result = result.filter(a => a.assettype === filterType.value)
  }

  if (showUnplacedOnly.value) {
    result = result.filter(a => !a.mapx || !a.mapy)
  }

  return result
})

const placedAssets = computed(() => {
  return assets.value.filter(a => a.mapx && a.mapy)
})

onMounted(async () => {
  await loadAssets()
})

async function loadAssets() {
  loading.value = true
  try {
    const response = await assetsApi.getMap()
    assets.value = response.data.data?.assets || []
  } catch (error) {
    console.error('Failed to load assets:', error)
  } finally {
    loading.value = false
  }
}

function getTypeIcon(assettype) {
  const icons = {
    'machine': Cog,
    'computer': Monitor,
    'printer': Printer,
    'network_device': Globe
  }
  return icons[assettype] || Package
}

function selectAsset(asset) {
  selectedAsset.value = asset
  pickedPosition.value = asset.mapx && asset.mapy
    ? { left: asset.mapx, top: asset.mapy }
    : null
}

function handlePositionPicked(position) {
  pickedPosition.value = position
}

function handleMarkerClick(asset) {
  selectAsset(asset)
}

async function savePosition() {
  if (!selectedAsset.value || !pickedPosition.value) return

  try {
    await assetsApi.update(selectedAsset.value.assetid, {
      mapx: Math.round(pickedPosition.value.left),
      mapy: Math.round(pickedPosition.value.top)
    })

    // Update local state
    const asset = assets.value.find(a => a.assetid === selectedAsset.value.assetid)
    if (asset) {
      asset.mapx = Math.round(pickedPosition.value.left)
      asset.mapy = Math.round(pickedPosition.value.top)
    }

    selectedAsset.value = null
    pickedPosition.value = null
  } catch (error) {
    console.error('Failed to save position:', error)
    toast.error('Failed to save position')
  }
}

async function clearPosition() {
  if (!selectedAsset.value) return

  if (!confirm(`Remove ${selectedAsset.value.name || selectedAsset.value.assetnumber} from the map?`)) return

  try {
    await assetsApi.update(selectedAsset.value.assetid, {
      mapx: null,
      mapy: null
    })

    // Update local state
    const asset = assets.value.find(a => a.assetid === selectedAsset.value.assetid)
    if (asset) {
      asset.mapx = null
      asset.mapy = null
    }

    selectedAsset.value = null
    pickedPosition.value = null
  } catch (error) {
    console.error('Failed to clear position:', error)
    toast.error('Failed to clear position')
  }
}

function cancelEdit() {
  selectedAsset.value = null
  pickedPosition.value = null
}
</script>

<style scoped>
.map-editor {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

.editor-layout {
  display: flex;
  flex: 1;
  gap: 1rem;
  min-height: 0;
}

.asset-panel {
  width: 320px;
  display: flex;
  flex-direction: column;
  background: var(--bg-card);
  border-radius: 8px;
  border: 1px solid var(--border);
  overflow: hidden;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid var(--border);
}

.panel-header h3 {
  margin: 0;
  font-size: 1rem;
}

.panel-header select {
  width: auto;
  padding: 0.375rem 0.5rem;
  font-size: 0.8rem;
}

.asset-filter {
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--border);
}

.filter-checkbox {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  cursor: pointer;
}

.asset-list {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem;
}

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

.asset-item:hover {
  background: var(--bg);
}

.asset-item.selected {
  background: rgba(65, 129, 255, 0.2);
  border: 1px solid var(--primary);
}

.asset-item.unplaced {
  opacity: 0.7;
}

.asset-icon {
  font-size: 1.5rem;
}

.asset-info {
  flex: 1;
  min-width: 0;
}

.asset-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.asset-meta {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.25rem;
}

.badge-sm {
  font-size: 0.7rem;
  padding: 0.15rem 0.4rem;
}

.placed-indicator {
  font-size: 0.875rem;
}

.map-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.map-toolbar {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem 1rem;
  background: var(--bg-card);
  border-radius: 8px;
  border: 1px solid var(--border);
  margin-bottom: 0.5rem;
  flex-wrap: wrap;
}

.selected-info {
  font-size: 0.9rem;
}

.position-info {
  font-size: 0.875rem;
  color: var(--text-light);
  font-family: monospace;
}

.toolbar-actions {
  display: flex;
  gap: 0.5rem;
  margin-left: auto;
}

.instruction {
  color: var(--text-light);
  font-style: italic;
}

.map-panel :deep(.shopfloor-map) {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;
}

.empty {
  padding: 2rem;
  text-align: center;
  color: var(--text-light);
}
</style>
