<template>
  <div>
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold text-slate-800">Fahrschulen</h1>
        <p class="text-slate-500 text-sm mt-1">Verwalten Sie alle registrierten Fahrschulen</p>
      </div>
      <button 
        @click="showCreateModal = true"
        class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-600 transition-colors"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
        </svg>
        Fahrschule anlegen
      </button>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow-sm p-4 mb-6">
      <div class="flex items-center gap-4">
        <div class="relative flex-1 max-w-md">
          <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            v-model="search"
            type="text"
            placeholder="Suchen..."
            class="w-full pl-10 pr-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary focus:border-primary outline-none"
          />
        </div>
        <select 
          v-model="statusFilter"
          class="px-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary focus:border-primary outline-none"
        >
          <option value="">Alle Status</option>
          <option value="pending_approval">Ausstehend</option>
          <option value="active">Aktiv</option>
          <option value="trial">Testphase</option>
          <option value="suspended">Suspendiert</option>
        </select>
      </div>
    </div>

    <!-- Table -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden">
      <table class="w-full">
        <thead class="bg-slate-50 border-b border-slate-200">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wider">Fahrschule</th>
            <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wider">Status</th>
            <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wider">Module</th>
            <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wider">Registriert</th>
            <th class="px-6 py-3 text-right text-xs font-semibold text-slate-600 uppercase tracking-wider">Aktionen</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-200">
          <tr v-for="tenant in filteredTenants" :key="tenant.id" class="hover:bg-slate-50">
            <td class="px-6 py-4">
              <div>
                <p class="font-medium text-slate-800">{{ tenant.name }}</p>
                <p class="text-sm text-slate-500">{{ tenant.email }}</p>
              </div>
            </td>
            <td class="px-6 py-4">
              <span 
                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                :class="statusClass(tenant.status)"
              >
                {{ statusLabel(tenant.status) }}
              </span>
            </td>
            <td class="px-6 py-4">
              <div class="flex items-center gap-1">
                <span 
                  v-for="mod in tenant.modules?.slice(0, 3)" 
                  :key="mod"
                  class="inline-flex items-center px-2 py-0.5 rounded text-xs bg-slate-100 text-slate-600"
                >
                  {{ mod }}
                </span>
                <span v-if="tenant.module_count > 3" class="text-xs text-slate-400">
                  +{{ tenant.module_count - 3 }}
                </span>
              </div>
            </td>
            <td class="px-6 py-4 text-sm text-slate-500">
              {{ formatDate(tenant.created_at) }}
            </td>
            <td class="px-6 py-4 text-right">
              <div class="flex items-center justify-end gap-2">
                <router-link 
                  :to="`/admin/tenants/${tenant.id}`"
                  class="p-2 text-slate-400 hover:text-primary rounded-lg hover:bg-slate-100 transition-colors"
                >
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                  </svg>
                </router-link>
                <button 
                  v-if="tenant.status === 'pending_approval'"
                  @click="approveTenant(tenant)"
                  class="p-2 text-slate-400 hover:text-green-600 rounded-lg hover:bg-green-50 transition-colors"
                  title="Genehmigen"
                >
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                  </svg>
                </button>
                <button 
                  v-if="tenant.status !== 'suspended'"
                  @click="suspendTenant(tenant)"
                  class="p-2 text-slate-400 hover:text-red-600 rounded-lg hover:bg-red-50 transition-colors"
                  title="Suspendieren"
                >
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                  </svg>
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="filteredTenants.length === 0">
            <td colspan="5" class="px-6 py-12 text-center text-slate-500">
              Keine Fahrschulen gefunden
            </td>
          </tr>
        </tbody>
      </table>

      <!-- Pagination -->
      <div class="px-6 py-4 border-t border-slate-200 flex items-center justify-between">
        <p class="text-sm text-slate-500">
          Zeige {{ pagination.start }} - {{ pagination.end }} von {{ pagination.total }}
        </p>
        <div class="flex items-center gap-2">
          <button 
            @click="page--" 
            :disabled="page === 1"
            class="px-3 py-1 rounded border border-slate-300 text-slate-600 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Zurück
          </button>
          <button 
            @click="page++" 
            :disabled="page >= pagination.pages"
            class="px-3 py-1 rounded border border-slate-300 text-slate-600 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Weiter
          </button>
        </div>
      </div>
    </div>

    <!-- Create Modal -->
    <div v-if="showCreateModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
      <div class="bg-white rounded-2xl shadow-xl w-full max-w-md p-6">
        <h3 class="text-lg font-semibold text-slate-800 mb-4">Fahrschule anlegen</h3>
        <form @submit.prevent="createTenant" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-slate-700 mb-1">Name *</label>
            <input v-model="newTenant.name" type="text" required class="w-full px-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary outline-none" />
          </div>
          <div>
            <label class="block text-sm font-medium text-slate-700 mb-1">E-Mail *</label>
            <input v-model="newTenant.email" type="email" required class="w-full px-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary outline-none" />
          </div>
          <div class="flex items-center gap-2 pt-2">
            <button type="button" @click="showCreateModal = false" class="px-4 py-2 rounded-lg border border-slate-300 text-slate-600 hover:bg-slate-50">
              Abbrechen
            </button>
            <button type="submit" :disabled="creating" class="px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary-600 disabled:opacity-50">
              {{ creating ? 'Erstelle...' : 'Erstellen' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import api from '@/api/client'

const tenants = ref([])
const loading = ref(true)
const search = ref('')
const statusFilter = ref('')
const page = ref(1)
const limit = ref(20)

const showCreateModal = ref(false)
const newTenant = reactive({ name: '', email: '' })
const creating = ref(false)

const filteredTenants = computed(() => {
  return tenants.value
})

const pagination = computed(() => ({
  start: (page.value - 1) * limit.value + 1,
  end: Math.min(page.value * limit.value, tenants.value.length),
  total: tenants.value.length,
  pages: Math.ceil(tenants.value.length / limit.value)
}))

async function fetchTenants() {
  loading.value = true
  try {
    const response = await api.get('/admin/tenants', { params: { page: page.value, limit: limit.value, status: statusFilter.value || undefined } })
    tenants.value = response.data.data.tenants
  } catch (error) {
    console.error('Failed to fetch tenants:', error)
  } finally {
    loading.value = false
  }
}

async function createTenant() {
  creating.value = true
  try {
    await api.post('/admin/tenants', newTenant)
    showCreateModal.value = false
    Object.assign(newTenant, { name: '', email: '' })
    await fetchTenants()
  } catch (error) {
    console.error('Failed to create tenant:', error)
  } finally {
    creating.value = false
  }
}

async function approveTenant(tenant) {
  try {
    await api.post(`/admin/tenants/${tenant.id}/approve`)
    await fetchTenants()
  } catch (error) {
    console.error('Failed to approve tenant:', error)
  }
}

async function suspendTenant(tenant) {
  try {
    await api.post(`/admin/tenants/${tenant.id}/suspend`)
    await fetchTenants()
  } catch (error) {
    console.error('Failed to suspend tenant:', error)
  }
}

function statusClass(status) {
  const classes = {
    pending_approval: 'bg-yellow-100 text-yellow-800',
    active: 'bg-green-100 text-green-800',
    trial: 'bg-blue-100 text-blue-800',
    suspended: 'bg-red-100 text-red-800'
  }
  return classes[status] || 'bg-slate-100 text-slate-800'
}

function statusLabel(status) {
  const labels = {
    pending_approval: 'Ausstehend',
    active: 'Aktiv',
    trial: 'Testphase',
    suspended: 'Suspendiert'
  }
  return labels[status] || status
}

function formatDate(date) {
  return new Date(date).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
}

onMounted(fetchTenants)
</script>