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

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

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>Machine Type</th>
                <th>Category</th>
                <th>Description</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="mt in machineTypes" :key="mt.machinetypeid">
                <td>{{ mt.machinetype }}</td>
                <td>
                  <span class="badge" :class="getCategoryClass(mt.category)">
                    {{ mt.category }}
                  </span>
                </td>
                <td>{{ mt.description || '-' }}</td>
                <td class="actions">
                  <button
                    class="btn btn-secondary btn-sm"
                    @click="openModal(mt)"
                  >
                    Edit
                  </button>
                  <button
                    class="btn btn-danger btn-sm"
                    @click="confirmDelete(mt)"
                  >
                    Delete
                  </button>
                </td>
              </tr>
              <tr v-if="machineTypes.length === 0">
                <td colspan="4" style="text-align: center; color: var(--text-light);">
                  No machine types found
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <PaginationBar
          :page="page"
          :totalPages="totalPages"
          :perPage="perPage"
          @update:page="goToPage"
          @update:perPage="changePerPage"
        />
      </template>
    </div>

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

            <div class="form-group">
              <label for="category">Category *</label>
              <select
                id="category"
                v-model="form.category"
                class="form-control"
                required
              >
                <option value="">Select category...</option>
                <option value="Equipment">Equipment</option>
                <option value="PC">PC</option>
                <option value="Network">Network</option>
                <option value="Printer">Printer</option>
              </select>
            </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 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 Machine Type</h3>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete <strong>{{ typeToDelete?.machinetype }}</strong>?</p>
          <p style="color: var(--text-light); font-size: 0.875rem;">
            This may affect machines using this type.
          </p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
          <button class="btn btn-danger" @click="deleteType">Delete</button>
        </div>
      </div>
    </div>
  </div>
</template>

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

const machineTypes = ref([])
const loading = ref(true)
const page = ref(1)
const totalPages = ref(1)
const perPage = ref(20)

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

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

const form = ref({
  machinetype: '',
  category: '',
  description: ''
})

onMounted(() => {
  loadTypes()
})

async function loadTypes() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      perpage: perPage.value
    }

    const response = await machinetypesApi.list(params)
    machineTypes.value = response.data.data || []
    totalPages.value = response.data.meta?.pagination?.totalpages || response.data.meta?.pagination?.total_pages || 1
  } catch (err) {
    console.error('Error loading machine types:', err)
  } finally {
    loading.value = false
  }
}

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

function changePerPage(newPerPage) {
  perPage.value = newPerPage
  page.value = 1
  loadTypes()
}

function openModal(mt = null) {
  editingType.value = mt
  if (mt) {
    form.value = {
      machinetype: mt.machinetype || '',
      category: mt.category || '',
      description: mt.description || ''
    }
  } else {
    form.value = {
      machinetype: '',
      category: '',
      description: ''
    }
  }
  error.value = ''
  showModal.value = true
}

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

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

  try {
    if (editingType.value) {
      await machinetypesApi.update(editingType.value.machinetypeid, form.value)
    } else {
      await machinetypesApi.create(form.value)
    }
    closeModal()
    loadTypes()
  } catch (err) {
    console.error('Error saving machine type:', err)
    error.value = err.response?.data?.message || 'Failed to save machine type'
  } finally {
    saving.value = false
  }
}

function confirmDelete(mt) {
  typeToDelete.value = mt
  showDeleteModal.value = true
}

async function deleteType() {
  try {
    await machinetypesApi.delete(typeToDelete.value.machinetypeid)
    showDeleteModal.value = false
    typeToDelete.value = null
    loadTypes()
  } catch (err) {
    console.error('Error deleting machine type:', err)
    alert('Failed to delete machine type')
  }
}

function getCategoryClass(category) {
  if (!category) return 'badge-info'
  const c = category.toLowerCase()
  if (c === 'equipment') return 'badge-info'
  if (c === 'pc') return 'badge-success'
  if (c === 'network') return 'badge-warning'
  if (c === 'printer') return 'badge-primary'
  return 'badge-info'
}
</script>

<!-- Uses global styles from style.css -->
