<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '@/api'

const loading = ref(true)
const objects = ref<any[]>([])
const selectedObject = ref<any>(null)
const showModal = ref(false)
const form = ref({ name: '', address: '', city: '', postal_code: '', customer_id: '' })

onMounted(async () => { await loadData() })

async function loadData() {
  loading.value = true
  try {
    const res = await api.get<any>('/objects')
    objects.value = res.data.objects || []
  } catch (e) { console.error(e) }
  loading.value = false
}

async function loadObject(id: string) {
  try {
    const res = await api.get<any>(`/objects/${id}`)
    selectedObject.value = res.data
  } catch (e) { console.error(e) }
}

async function createObject() {
  try {
    await api.post('/objects', form.value)
    showModal.value = false
    form.value = { name: '', address: '', city: '', postal_code: '', customer_id: '' }
    await loadData()
  } catch (e: any) { alert('Fehler: ' + e.message) }
}

function statusBadge(s: string) {
  const map: Record<string, any> = {
    active: { text: 'Aktiv', class: 'bg-green-100 text-green-700', icon: '🟢' },
    inactive: { text: 'Inaktiv', class: 'bg-gray-100 text-gray-700', icon: '⚪' },
    pending: { text: 'Ausstehend', class: 'bg-yellow-100 text-yellow-700', icon: '🟡' }
  }
  return map[s] || { text: s, class: 'bg-gray-100', icon: '' }
}
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-2xl font-bold">🏢 Objektverwaltung</h1>
        <p class="text-gray-500">Standorte, Kontakte & Anweisungen</p>
      </div>
      <button @click="showModal = true" class="btn btn-primary">+ Objekt</button>
    </div>

    <div class="flex gap-6">
      <!-- Object List -->
      <div class="w-1/2">
        <div v-if="loading" class="text-center py-12">Laden...</div>
        
        <div v-else-if="objects.length === 0" class="bg-gray-50 rounded-lg p-12 text-center text-gray-500">
          <p class="text-4xl mb-4">🏢</p>
          <p>Keine Objekte vorhanden</p>
        </div>

        <div v-else class="space-y-2">
          <div v-for="obj in objects" :key="obj.id" 
               @click="loadObject(obj.id)"
               :class="['bg-white rounded-lg shadow p-4 cursor-pointer hover:shadow-md transition-shadow',
                        selectedObject?.id === obj.id ? 'ring-2 ring-blue-500' : '']">
            <div class="flex justify-between items-start">
              <div>
                <h3 class="font-semibold">{{ obj.name }}</h3>
                <p class="text-sm text-gray-500">{{ obj.address }}</p>
                <p class="text-sm text-gray-400">{{ obj.postal_code }} {{ obj.city }}</p>
              </div>
              <span :class="['px-2 py-1 text-xs rounded', statusBadge(obj.status).class]">
                {{ statusBadge(obj.status).icon }} {{ statusBadge(obj.status).text }}
              </span>
            </div>
            <div v-if="obj.customer_name" class="mt-2 text-xs text-gray-500">
              👤 {{ obj.customer_name }}
            </div>
          </div>
        </div>
      </div>

      <!-- Object Detail -->
      <div class="w-1/2">
        <div v-if="!selectedObject" class="bg-gray-50 rounded-lg p-12 text-center text-gray-400">
          <p>Wähle ein Objekt aus</p>
        </div>
        
        <div v-else class="bg-white rounded-lg shadow p-6">
          <h2 class="text-xl font-bold mb-1">{{ selectedObject.name }}</h2>
          <p class="text-gray-500 mb-4">{{ selectedObject.address }}, {{ selectedObject.postal_code }} {{ selectedObject.city }}</p>
          
          <div class="space-y-6">
            <!-- Contacts -->
            <div>
              <h3 class="text-sm font-semibold text-gray-500 mb-2 flex items-center">
                📞 Ansprechpartner 
                <span class="ml-2 text-xs bg-gray-100 px-2 py-0.5 rounded">{{ selectedObject.contacts?.length || 0 }}</span>
              </h3>
              <div v-if="selectedObject.contacts?.length" class="space-y-2">
                <div v-for="c in selectedObject.contacts" :key="c.id" class="p-2 bg-gray-50 rounded text-sm">
                  <div class="font-medium">{{ c.name }} <span class="text-gray-400 font-normal">{{ c.role }}</span></div>
                  <div class="text-gray-600">📞 {{ c.phone }} · 📧 {{ c.email }}</div>
                </div>
              </div>
              <p v-else class="text-sm text-gray-400">Keine Kontakte hinterlegt</p>
            </div>

            <!-- Instructions -->
            <div>
              <h3 class="text-sm font-semibold text-gray-500 mb-2 flex items-center">
                📋 Anweisungen
                <span class="ml-2 text-xs bg-gray-100 px-2 py-0.5 rounded">{{ selectedObject.instructions?.length || 0 }}</span>
              </h3>
              <div v-if="selectedObject.instructions?.length" class="space-y-2">
                <div v-for="ins in selectedObject.instructions" :key="ins.id" 
                     :class="['p-2 rounded text-sm', ins.priority === 'critical' ? 'bg-red-50 border-l-4 border-red-500' : 
                              ins.priority === 'high' ? 'bg-orange-50 border-l-4 border-orange-500' : 'bg-gray-50']">
                  <div class="font-medium">{{ ins.title }}</div>
                  <p class="text-gray-600">{{ ins.content }}</p>
                </div>
              </div>
              <p v-else class="text-sm text-gray-400">Keine Anweisungen hinterlegt</p>
            </div>

            <!-- Documents -->
            <div v-if="selectedObject.documents?.length">
              <h3 class="text-sm font-semibold text-gray-500 mb-2">📁 Dokumente</h3>
              <div class="flex flex-wrap gap-2">
                <a v-for="d in selectedObject.documents" :key="d.id" 
                   :href="d.file_url" target="_blank"
                   class="px-2 py-1 bg-blue-50 text-blue-700 rounded text-sm hover:bg-blue-100">
                  {{ d.file_name || 'Dokument' }}
                </a>
              </div>
            </div>

            <!-- Checkpoints -->
            <div v-if="selectedObject.checkpoints?.length">
              <h3 class="text-sm font-semibold text-gray-500 mb-2">📍 Checkpoints</h3>
              <div class="flex flex-wrap gap-2">
                <span v-for="cp in selectedObject.checkpoints" :key="cp.id" 
                      class="px-2 py-1 bg-gray-100 rounded text-sm">
                  {{ cp.name }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal -->
    <div v-if="showModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h2 class="text-xl font-bold mb-4">Neues Objekt</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Name *</label>
            <input v-model="form.name" class="input" placeholder="z.B. Hauptgebäude Musterstraße" />
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Adresse</label>
            <input v-model="form.address" class="input" />
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">PLZ</label>
              <input v-model="form.postal_code" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Stadt</label>
              <input v-model="form.city" class="input" />
            </div>
          </div>
        </div>
        <div class="flex justify-end space-x-2 mt-6">
          <button @click="showModal = false" class="btn">Abbrechen</button>
          <button @click="createObject" class="btn btn-primary">Erstellen</button>
        </div>
      </div>
    </div>
  </div>
</template>
