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

    <!-- Search -->
    <div class="filters">
      <input
        v-model="search"
        type="text"
        class="form-control"
        placeholder="Search locations..."
        @input="debouncedSearch"
      />
    </div>

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

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>Location Name</th>
                <th>Building</th>
                <th>Floor</th>
                <th>Room</th>
                <th>Description</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="loc in locations" :key="loc.locationid">
                <td>{{ loc.locationname }}</td>
                <td>{{ loc.building || '-' }}</td>
                <td>{{ loc.floor || '-' }}</td>
                <td>{{ loc.room || '-' }}</td>
                <td>{{ loc.description || '-' }}</td>
                <td class="actions">
                  <button
                    class="btn btn-secondary btn-sm"
                    @click="openModal(loc)"
                  >
                    Edit
                  </button>
                  <button
                    class="btn btn-danger btn-sm"
                    @click="confirmDelete(loc)"
                  >
                    Delete
                  </button>
                </td>
              </tr>
              <tr v-if="locations.length === 0">
                <td colspan="6" style="text-align: center; color: var(--text-light);">
                  No locations found
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <div class="pagination" v-if="totalPages > 1">
          <button
            v-for="p in totalPages"
            :key="p"
            :class="{ active: p === page }"
            @click="goToPage(p)"
          >
            {{ p }}
          </button>
        </div>
      </template>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ editingLocation ? 'Edit Location' : 'Add Location' }}</h3>
        </div>
        <form @submit.prevent="saveLocation">
          <div class="modal-body">
            <div class="form-group">
              <label for="locationname">Location Name *</label>
              <input
                id="locationname"
                v-model="form.locationname"
                type="text"
                class="form-control"
                required
              />
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="building">Building</label>
                <input
                  id="building"
                  v-model="form.building"
                  type="text"
                  class="form-control"
                />
              </div>

              <div class="form-group">
                <label for="floor">Floor</label>
                <input
                  id="floor"
                  v-model="form.floor"
                  type="text"
                  class="form-control"
                />
              </div>

              <div class="form-group">
                <label for="room">Room</label>
                <input
                  id="room"
                  v-model="form.room"
                  type="text"
                  class="form-control"
                />
              </div>
            </div>

            <div class="form-group">
              <label for="description">Description</label>
              <textarea
                id="description"
                v-model="form.description"
                class="form-control"
                rows="3"
              ></textarea>
            </div>

            <div class="form-group">
              <label for="mapimage">Map Image URL</label>
              <input
                id="mapimage"
                v-model="form.mapimage"
                type="text"
                class="form-control"
                placeholder="Optional floor plan image URL"
              />
            </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 Confirmation Modal -->
    <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
      <div class="modal">
        <div class="modal-header">
          <h3>Delete Location</h3>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete <strong>{{ locationToDelete?.locationname }}</strong>?</p>
          <p style="color: var(--text-light); font-size: 0.875rem;">
            This may affect machines assigned to this location.
          </p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
          <button class="btn btn-danger" @click="deleteLocation">Delete</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { locationsApi } from '../../api'

const locations = ref([])
const loading = ref(true)
const search = ref('')
const page = ref(1)
const totalPages = ref(1)

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

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

const form = ref({
  locationname: '',
  building: '',
  floor: '',
  room: '',
  description: '',
  mapimage: ''
})

let searchTimeout = null

onMounted(() => {
  loadLocations()
})

async function loadLocations() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      perpage: 20
    }
    if (search.value) params.search = search.value

    const response = await locationsApi.list(params)
    locations.value = response.data.data || []
    totalPages.value = response.data.meta?.pages || 1
  } catch (err) {
    console.error('Error loading locations:', err)
  } finally {
    loading.value = false
  }
}

function debouncedSearch() {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    page.value = 1
    loadLocations()
  }, 300)
}

function goToPage(p) {
  page.value = p
  loadLocations()
}

function openModal(loc = null) {
  editingLocation.value = loc
  if (loc) {
    form.value = {
      locationname: loc.locationname || '',
      building: loc.building || '',
      floor: loc.floor || '',
      room: loc.room || '',
      description: loc.description || '',
      mapimage: loc.mapimage || ''
    }
  } else {
    form.value = {
      locationname: '',
      building: '',
      floor: '',
      room: '',
      description: '',
      mapimage: ''
    }
  }
  error.value = ''
  showModal.value = true
}

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

async function saveLocation() {
  error.value = ''
  saving.value = true

  try {
    if (editingLocation.value) {
      await locationsApi.update(editingLocation.value.locationid, form.value)
    } else {
      await locationsApi.create(form.value)
    }
    closeModal()
    loadLocations()
  } catch (err) {
    console.error('Error saving location:', err)
    error.value = err.response?.data?.message || 'Failed to save location'
  } finally {
    saving.value = false
  }
}

function confirmDelete(loc) {
  locationToDelete.value = loc
  showDeleteModal.value = true
}

async function deleteLocation() {
  try {
    await locationsApi.delete(locationToDelete.value.locationid)
    showDeleteModal.value = false
    locationToDelete.value = null
    loadLocations()
  } catch (err) {
    console.error('Error deleting location:', err)
    alert('Failed to delete location')
  }
}
</script>

<style scoped>
.form-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}
</style>
