<template>
  <div>
    <div class="flex items-center gap-4 mb-6">
      <button @click="$router.back()" class="p-2 rounded-lg hover:bg-slate-100">
        <svg class="w-5 h-5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
        </svg>
      </button>
      <div>
        <h1 class="text-2xl font-bold text-slate-800">{{ tenant?.name || 'Laden...' }}</h1>
        <p class="text-slate-500 text-sm">Fahrschule bearbeiten</p>
      </div>
    </div>

    <div v-if="loading" class="text-center py-12 text-slate-500">Laden...</div>
    
    <div v-else-if="tenant" class="grid gap-6">
      <!-- Info Card -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <h2 class="text-lg font-semibold mb-4">Stammdaten</h2>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-slate-700 mb-1">Name</label>
            <input v-model="tenant.name" class="w-full px-4 py-2 rounded-lg border border-slate-300" />
          </div>
          <div>
            <label class="block text-sm font-medium text-slate-700 mb-1">E-Mail</label>
            <input v-model="tenant.email" class="w-full px-4 py-2 rounded-lg border border-slate-300" />
          </div>
          <div>
            <label class="block text-sm font-medium text-slate-700 mb-1">Telefon</label>
            <input v-model="tenant.phone" class="w-full px-4 py-2 rounded-lg border border-slate-300" />
          </div>
          <div>
            <label class="block text-sm font-medium text-slate-700 mb-1">Status</label>
            <select v-model="tenant.status" class="w-full px-4 py-2 rounded-lg border border-slate-300">
              <option value="pending_approval">Ausstehend</option>
              <option value="active">Aktiv</option>
              <option value="trial">Testphase</option>
              <option value="suspended">Suspendiert</option>
            </select>
          </div>
        </div>
        <button @click="save" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-600">
          Speichern
        </button>
      </div>

      <!-- Modules Card -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <h2 class="text-lg font-semibold mb-4">Module</h2>
        <div class="space-y-2">
          <div v-for="mod in allModules" :key="mod.id" class="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
            <div>
              <p class="font-medium">{{ mod.name }}</p>
              <p class="text-sm text-slate-500">{{ mod.description }}</p>
            </div>
            <button 
              @click="toggleModule(mod)"
              class="px-3 py-1 rounded text-sm"
              :class="isModuleEnabled(mod.id) ? 'bg-green-100 text-green-700' : 'bg-slate-200 text-slate-600'"
            >
              {{ isModuleEnabled(mod.id) ? 'Aktiv' : 'Inaktiv' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import api from '@/api/client'

const route = useRoute()
const tenant = ref(null)
const allModules = ref([])
const loading = ref(true)

async function fetch() {
  loading.value = true
  try {
    const [tenantRes, modulesRes] = await Promise.all([
      api.get(`/admin/tenants/${route.params.id}`),
      api.get('/admin/platform-modules')
    ])
    tenant.value = tenantRes.data.data
    allModules.value = modulesRes.data.data
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

function isModuleEnabled(moduleId) {
  return tenant.value?.modules?.some(m => m.id === moduleId && m.status === 'enabled')
}

async function toggleModule(mod) {
  const current = isModuleEnabled(mod.id)
  try {
    if (current) {
      await api.delete(`/admin/tenants/${tenant.value.id}/modules/${mod.id}`)
    } else {
      await api.post(`/admin/tenants/${tenant.value.id}/modules`, { module_id: mod.id })
    }
    await fetch()
  } catch (e) {
    console.error(e)
  }
}

async function save() {
  try {
    await api.put(`/admin/tenants/${tenant.value.id}`, {
      name: tenant.value.name,
      email: tenant.value.email,
      phone: tenant.value.phone,
      status: tenant.value.status
    })
    alert('Gespeichert!')
  } catch (e) {
    console.error(e)
    alert('Fehler beim Speichern')
  }
}

onMounted(fetch)
</script>