<template>
  <div>
    <div class="page-header">
      <h2>Model 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>Model Type</th>
                <th>Category</th>
                <th>Description</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="mt in modelTypes" :key="mt.modeltypeid">
                <td>{{ mt.modeltype }}</td>
                <td>
                  <span class="badge" :class="getCategoryClass(mt.category)">
                    {{ mt.category }}
                  </span>
                </td>
                <td class="cell-truncate" :title="mt.description">{{ 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="modelTypes.length === 0">
                <td colspan="4" style="text-align: center; color: var(--text-light);">
                  No model 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">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ editingType ? 'Edit Model Type' : 'Add Model Type' }}</h3>
        </div>
        <form @submit.prevent="saveType">
          <div class="modal-body">
            <div class="form-group">
              <label for="modeltype">Type Name *</label>
              <input
                id="modeltype"
                v-model="form.modeltype"
                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 Model Type</h3>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete <strong>{{ typeToDelete?.modeltype }}</strong>?</p>
          <p style="color: var(--text-light); font-size: 0.875rem;">
            This may affect models 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 { modeltypesApi } from '../../api'
import PaginationBar from '../../components/PaginationBar.vue'
import { useToast } from '../../composables/toast'
import { apiError } from '../../utils/apiError'
import { useListQuery } from '@/composables/listQuery'
const toast = useToast()

const modelTypes = ref([])
const loading = ref(true)
const { page, setPage } = useListQuery({ onChange: loadTypes })
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({
  modeltype: '',
  category: '',
  description: ''
})

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

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

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

function goToPage(p) {
  setPage(p)
  loadTypes()
}

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

function openModal(mt = null) {
  editingType.value = mt
  if (mt) {
    form.value = {
      modeltype: mt.modeltype || '',
      category: mt.category || '',
      description: mt.description || ''
    }
  } else {
    form.value = {
      modeltype: '',
      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 modeltypesApi.update(editingType.value.modeltypeid, form.value)
    } else {
      await modeltypesApi.create(form.value)
    }
    closeModal()
    loadTypes()
  } catch (err) {
    console.error('Error saving model type:', err)
    error.value = apiError(err, 'Failed to save model type')
  } finally {
    saving.value = false
  }
}

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

async function deleteType() {
  try {
    await modeltypesApi.delete(typeToDelete.value.modeltypeid)
    showDeleteModal.value = false
    typeToDelete.value = null
    loadTypes()
  } catch (err) {
    console.error('Error deleting model type:', err)
    toast.error('Failed to delete model 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 -->
