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

    <!-- Filters -->
    <div class="filters">
      <input
        v-model="search"
        type="text"
        class="form-control"
        placeholder="Search models..."
        @input="debouncedSearch"
      />
      <select v-model="vendorFilter" class="form-control" @change="loadModels">
        <option value="">All Vendors</option>
        <option v-for="v in vendors" :key="v.vendorid" :value="v.vendorid">
          {{ v.vendor }}
        </option>
      </select>
    </div>

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

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>Model</th>
                <th>Vendor</th>
                <th>Type</th>
                <th>Documentation</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="m in models" :key="m.modelnumberid">
                <td>
                  <div>{{ m.modelnumber }}</div>
                  <small v-if="m.description" class="text-muted">{{ m.description }}</small>
                </td>
                <td>{{ m.vendor || '-' }}</td>
                <td>{{ m.machinetype || '-' }}</td>
                <td>
                  <a v-if="m.documentationurl" :href="m.documentationurl" target="_blank" class="btn btn-sm btn-link">
                    View Docs
                  </a>
                  <span v-else>-</span>
                </td>
                <td class="actions">
                  <button class="btn btn-secondary btn-sm" @click="openModal(m)">Edit</button>
                  <button class="btn btn-danger btn-sm" @click="confirmDelete(m)">Delete</button>
                </td>
              </tr>
              <tr v-if="models.length === 0">
                <td colspan="5" style="text-align: center; color: var(--text-light);">
                  No models 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 modal-lg">
        <div class="modal-header">
          <h3>{{ editingModel ? 'Edit Model' : 'Add Model' }}</h3>
        </div>
        <form @submit.prevent="saveModel">
          <div class="modal-body">
            <div class="form-row">
              <div class="form-group">
                <label for="modelnumber">Model Number *</label>
                <input
                  id="modelnumber"
                  v-model="form.modelnumber"
                  type="text"
                  class="form-control"
                  required
                />
              </div>
              <div class="form-group">
                <label for="vendorid">Vendor *</label>
                <select id="vendorid" v-model="form.vendorid" class="form-control" required>
                  <option value="">Select vendor...</option>
                  <option v-for="v in vendors" :key="v.vendorid" :value="v.vendorid">
                    {{ v.vendor }}
                  </option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="machinetypeid">Machine Type</label>
                <select id="machinetypeid" v-model="form.machinetypeid" class="form-control">
                  <option value="">Select type...</option>
                  <option v-for="mt in machineTypes" :key="mt.machinetypeid" :value="mt.machinetypeid">
                    {{ mt.machinetype }}
                  </option>
                </select>
              </div>
              <div class="form-group">
                <label for="description">Description</label>
                <input id="description" v-model="form.description" type="text" class="form-control" />
              </div>
            </div>

            <div class="form-group">
              <label for="documentationurl">Documentation URL</label>
              <input
                id="documentationurl"
                v-model="form.documentationurl"
                type="url"
                class="form-control"
                placeholder="https://..."
              />
            </div>

            <div class="form-group">
              <label for="imageurl">Image URL</label>
              <input
                id="imageurl"
                v-model="form.imageurl"
                type="url"
                class="form-control"
                placeholder="https://..."
              />
            </div>

            <div class="form-group">
              <label for="notes">Notes</label>
              <textarea id="notes" v-model="form.notes" class="form-control" rows="2"></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</h3>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to delete <strong>{{ modelToDelete?.modelnumber }}</strong>?</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
          <button class="btn btn-danger" @click="deleteModel">Delete</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { modelsApi, vendorsApi, machinetypesApi } from '../../api'
import PaginationBar from '../../components/PaginationBar.vue'
import { useToast } from '../../composables/toast'
import { apiError } from '../../utils/apiError'
const toast = useToast()

const models = ref([])
const vendors = ref([])
const machineTypes = ref([])
const loading = ref(true)
const search = ref('')
const vendorFilter = ref('')
const page = ref(1)
const totalPages = ref(1)
const perPage = ref(20)

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

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

const form = ref({
  modelnumber: '',
  vendorid: '',
  machinetypeid: '',
  description: '',
  documentationurl: '',
  imageurl: '',
  notes: ''
})

let searchTimeout = null

onMounted(async () => {
  await Promise.all([
    loadModels(),
    loadVendors(),
    loadMachineTypes()
  ])
})

async function loadModels() {
  loading.value = true
  try {
    const params = { page: page.value, perpage: perPage.value }
    if (search.value) params.search = search.value
    if (vendorFilter.value) params.vendor = vendorFilter.value

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

async function loadVendors() {
  try {
    const response = await vendorsApi.list({ perpage: 100 })
    vendors.value = response.data.data || []
  } catch (err) {
    console.error('Error loading vendors:', err)
  }
}

async function loadMachineTypes() {
  try {
    const response = await machinetypesApi.list({ perpage: 100 })
    machineTypes.value = response.data.data || []
  } catch (err) {
    console.error('Error loading machine types:', err)
  }
}

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

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

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

function openModal(m = null) {
  editingModel.value = m
  if (m) {
    form.value = {
      modelnumber: m.modelnumber || '',
      vendorid: m.vendorid || '',
      machinetypeid: m.machinetypeid || '',
      description: m.description || '',
      documentationurl: m.documentationurl || '',
      imageurl: m.imageurl || '',
      notes: m.notes || ''
    }
  } else {
    form.value = {
      modelnumber: '',
      vendorid: '',
      machinetypeid: '',
      description: '',
      documentationurl: '',
      imageurl: '',
      notes: ''
    }
  }
  error.value = ''
  showModal.value = true
}

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

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

  try {
    const data = { ...form.value }
    if (!data.vendorid) data.vendorid = null
    if (!data.machinetypeid) data.machinetypeid = null

    if (editingModel.value) {
      await modelsApi.update(editingModel.value.modelnumberid, data)
    } else {
      await modelsApi.create(data)
    }
    closeModal()
    loadModels()
  } catch (err) {
    console.error('Error saving model:', err)
    error.value = apiError(err, 'Failed to save model')
  } finally {
    saving.value = false
  }
}

function confirmDelete(m) {
  modelToDelete.value = m
  showDeleteModal.value = true
}

async function deleteModel() {
  try {
    await modelsApi.delete(modelToDelete.value.modelnumberid)
    showDeleteModal.value = false
    modelToDelete.value = null
    loadModels()
  } catch (err) {
    console.error('Error deleting model:', err)
    toast.error('Failed to delete model')
  }
}
</script>

<style scoped>
.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.modal-lg {
  max-width: 600px;
}

.text-muted {
  color: var(--text-light);
  font-size: 0.85rem;
}
</style>
