<template>
  <div>
    <div class="page-header">
      <h2>Dashboard Defaults</h2>
      <button class="btn btn-primary" @click="openModal()">+ Add Mapping</button>
    </div>

    <p class="setting-description">
      Map a display PC's IP address to what it should show: the shopfloor
      dashboard (and which business unit), the lobby slideshow, or the 3D parts
      kiosk. A single "display" image resolves its role from its own IP.
    </p>

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

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>Kiosk (FQDN / IP)</th>
                <th>Display</th>
                <th>Location</th>
                <th>Description</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="d in items" :key="d.dashboarddefaultid">
                <td class="mono">{{ d.fqdn || d.ipaddress }}</td>
                <td>{{ roleLabel(d.displayrole) }}</td>
                <td>{{ d.businessunit || '-' }}</td>
                <td class="cell-truncate" :title="d.description">{{ d.description || '-' }}</td>
                <td class="actions">
                  <button class="btn btn-secondary btn-sm" @click="openModal(d)">Edit</button>
                  <button class="btn btn-danger btn-sm" @click="confirmDelete(d)">Delete</button>
                </td>
              </tr>
              <tr v-if="items.length === 0">
                <td colspan="5" style="text-align: center; color: var(--text-light);">
                  No mappings yet
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </template>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ editing ? 'Edit Mapping' : 'Add Mapping' }}</h3>
        </div>
        <form @submit.prevent="save">
          <div class="modal-body">
            <div class="form-group">
              <label for="kiosk">Kiosk</label>
              <select id="kiosk" v-model="form.fqdn" class="form-control">
                <option value="">Select a kiosk (or enter an IP below)...</option>
                <option v-for="k in kiosks" :key="k.computerid" :value="k.fqdn" :disabled="!k.fqdn">
                  {{ k.hostname }}{{ k.fqdn ? ' - ' + k.fqdn : ' (no serial reported yet)' }}
                </option>
              </select>
              <small class="form-hint">Pick a reporting display to fill its FQDN, or enter an IP manually below.</small>
            </div>
            <div class="form-group">
              <label for="ipaddress">IP Address (optional)</label>
              <input id="ipaddress" v-model="form.ipaddress" type="text" class="form-control"
                     placeholder="e.g., 10.20.30.40" />
            </div>
            <div class="form-group">
              <label for="displayrole">Display *</label>
              <select id="displayrole" v-model="form.displayrole" class="form-control" required>
                <option v-for="r in roleOptions" :key="r.value" :value="r.value">{{ r.label }}</option>
              </select>
            </div>
            <div class="form-group" v-if="form.displayrole === 'Dashboard'">
              <label for="businessunitid">Location *</label>
              <select id="businessunitid" v-model="form.businessunitid" class="form-control"
                      :required="form.displayrole === 'Dashboard'">
                <option value="">Select location...</option>
                <option v-for="bu in businessUnits" :key="bu.businessunitid" :value="bu.businessunitid">
                  {{ bu.businessunit }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label for="description">Description</label>
              <input id="description" v-model="form.description" type="text" class="form-control"
                     placeholder="e.g., Materials lobby kiosk" />
            </div>
            <div v-if="error" class="error-message">{{ error }}</div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="closeModal">Cancel</button>
            <button type="submit" class="btn btn-primary" :disabled="saving">
              {{ saving ? 'Saving...' : 'Save' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Modal -->
    <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
      <div class="modal">
        <div class="modal-header"><h3>Delete Mapping</h3></div>
        <div class="modal-body">
          <p>Delete the mapping for <strong>{{ toDelete?.ipaddress }}</strong>?</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
          <button class="btn btn-danger" @click="deleteItem">Delete</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { dashboardDefaultsApi, businessUnitsApi, computersApi } from '../../api'
import { useToast } from '../../composables/toast'
import { apiError } from '../../utils/apiError'
const toast = useToast()

// Values are the kiosk's own vocabulary - the literal contents of
// C:\Enrollment\display-type.txt - so what is picked here is what a display
// reports. Must stay in step with DISPLAY_ROLE_PATHS in
// shopdb/core/models/dashboarddefault.py.
const roleOptions = [
  { value: 'Dashboard', label: 'Shopfloor Dashboard' },
  { value: 'Lobby', label: 'Lobby Slideshow' },
  { value: '3DPrintRoom', label: '3D Print Room Kiosk' },
]
// Rows written before the vocabularies merged still carry the old spelling, so
// match case-insensitively and fall back to the retired name.
const legacyRoleLabels = { partskiosk: '3D Print Room Kiosk' }
const legacyRoleValues = { partskiosk: '3DPrintRoom' }
// Canonical value for any stored spelling. Without this, opening a row saved
// before the merge puts a value in the select that matches no option, and the
// dropdown renders blank as if the row had no role.
function canonicalRole(value) {
  const wanted = (value || '').toLowerCase()
  return roleOptions.find(r => r.value.toLowerCase() === wanted)?.value
    || legacyRoleValues[wanted]
    || 'Dashboard'
}
function roleLabel(value) {
  const wanted = (value || '').toLowerCase()
  return roleOptions.find(r => r.value.toLowerCase() === wanted)?.label
    || legacyRoleLabels[wanted]
    || value
}

const items = ref([])
const businessUnits = ref([])
const kiosks = ref([])
const loading = ref(true)

const showModal = ref(false)
const editing = ref(null)
const saving = ref(false)
const error = ref('')

const showDeleteModal = ref(false)
const toDelete = ref(null)

const form = ref({ fqdn: '', ipaddress: '', displayrole: 'Dashboard', businessunitid: '', description: '' })

onMounted(async () => {
  try {
    const response = await businessUnitsApi.list({ perpage: 100 })
    businessUnits.value = response.data.data || []
  } catch (err) {
    console.error('Error loading business units:', err)
  }
  try {
    const kioskResp = await computersApi.displayKiosks()
    kiosks.value = kioskResp.data.data || []
  } catch (err) {
    console.error('Error loading display kiosks:', err)
  }
  await loadData()
})

async function loadData() {
  loading.value = true
  try {
    const response = await dashboardDefaultsApi.list()
    items.value = response.data.data || []
  } catch (err) {
    console.error('Error loading dashboard defaults:', err)
  } finally {
    loading.value = false
  }
}

function openModal(item = null) {
  editing.value = item
  form.value = item ? {
    fqdn: item.fqdn || '',
    ipaddress: item.ipaddress || '',
    displayrole: canonicalRole(item.displayrole),
    businessunitid: item.businessunitid || '',
    description: item.description || ''
  } : { fqdn: '', ipaddress: '', displayrole: 'Dashboard', businessunitid: '', description: '' }
  error.value = ''
  showModal.value = true
}

function closeModal() { showModal.value = false; editing.value = null }

async function save() {
  error.value = ''
  saving.value = true
  try {
    if (editing.value) {
      await dashboardDefaultsApi.update(editing.value.dashboarddefaultid, form.value)
    } else {
      await dashboardDefaultsApi.create(form.value)
    }
    closeModal()
    loadData()
  } catch (err) {
    error.value = apiError(err, 'Failed to save')
  } finally {
    saving.value = false
  }
}

function confirmDelete(item) { toDelete.value = item; showDeleteModal.value = true }

async function deleteItem() {
  try {
    await dashboardDefaultsApi.delete(toDelete.value.dashboarddefaultid)
    showDeleteModal.value = false
    toDelete.value = null
    loadData()
  } catch (err) {
    toast.error('Failed to delete')
  }
}
</script>
