<template>
  <div>
    <div class="page-header">
      <h2>Measuring Tool Types</h2>
      <label class="show-inactive"><input type="checkbox" v-model="showInactive" /> Show inactive</label>
      <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>Type</th>
                <th>Description</th>
                <th>Color</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="mt in visibleTypes" :key="mt.measuringtooltypeid">
                <td>{{ mt.name }}</td>
                <td class="cell-truncate" :title="mt.description">{{ mt.description || '-' }}</td>
                <td>
                  <span class="badge" :style="colorStyle(mt.color)">{{ mt.color || 'auto' }}</span>
                </td>
                <td class="actions">
                  <span v-if="mt.isactive === false" class="badge badge-secondary" style="margin-right:6px;">inactive</span>
                  <button class="btn btn-secondary btn-sm" @click="openModal(mt)">Edit</button>
                  <button class="btn btn-danger btn-sm" @click="deleteType(mt)">Delete</button>
                </td>
              </tr>
              <tr v-if="visibleTypes.length === 0">
                <td colspan="4" style="text-align: center; color: var(--text-light);">
                  No measuring tool types found
                </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 Type' : 'Add Type' }}</h3>
        </div>
        <form @submit.prevent="save">
          <div class="modal-body">
            <div class="form-group">
              <label for="name">Type *</label>
              <input id="name" v-model="form.name" type="text" class="form-control" required />
            </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>Color <span class="hint">(map markers; blank = auto)</span></label>
              <ColorSwatchPicker v-model="form.color" />
            </div>
            <div class="form-group">
              <label class="checkbox-label"><input type="checkbox" v-model="form.isactive" /> Active</label>
            </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>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { measuringtoolsApi } from '@/api'
import ColorSwatchPicker from '@/components/ColorSwatchPicker.vue'
import { colorStyle } from '@/utils/colorStyle'
import { useToast } from '@/composables/toast'
import { apiError } from '@/utils/apiError'
const toast = useToast()

const types = ref([])
const showInactive = ref(false)
const visibleTypes = computed(() => showInactive.value ? types.value : types.value.filter(x => x.isactive !== false))
const loading = ref(true)

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

const form = ref({ name: '', description: '', color: '', isactive: true })

onMounted(() => loadData())

async function loadData() {
  loading.value = true
  try {
    const response = await measuringtoolsApi.types.list({ perpage: 200, active: false })
    types.value = response.data.data || []
  } catch (err) {
    console.error('Error loading measuring tool types:', err)
  } finally {
    loading.value = false
  }
}

function openModal(item = null) {
  editing.value = item
  form.value = item
    ? { name: item.name || '', description: item.description || '', color: item.color || '', isactive: item.isactive !== false }
    : { name: '', description: '', color: '', isactive: true }
  error.value = ''
  showModal.value = true
}

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

async function deleteType(mt) {
  if (!confirm(`Delete measuring tool type "${mt.name}"?`)) return
  try {
    await measuringtoolsApi.types.remove(mt.measuringtooltypeid)
    loadData()
  } catch (err) {
    toast.error(apiError(err, 'Failed to delete'))
  }
}

async function save() {
  error.value = ''
  saving.value = true
  try {
    if (editing.value) {
      await measuringtoolsApi.types.update(editing.value.measuringtooltypeid, form.value)
    } else {
      await measuringtoolsApi.types.create(form.value)
    }
    closeModal()
    loadData()
  } catch (err) {
    error.value = apiError(err, 'Failed to save')
  } finally {
    saving.value = false
  }
}
</script>
