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

const loading = ref(true)
const invoices = ref<any[]>([])
const rates = ref<any[]>([])
const stats = ref<any>({})
const activeTab = ref<'invoices' | 'rates'>('invoices')

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

async function loadData() {
  loading.value = true
  try {
    const [invRes, ratesRes, statsRes] = await Promise.all([
      api.get<any>('/billing/invoices'),
      api.get<any>('/billing/rates'),
      api.get<any>('/billing/stats')
    ])
    invoices.value = invRes.data.invoices || []
    rates.value = ratesRes.data.rates || []
    stats.value = statsRes.data.stats || {}
  } catch (e) { console.error(e) }
  loading.value = false
}

async function sendInvoice(id: string) {
  try {
    await api.put(`/billing/invoices/${id}/send`, {})
    await loadData()
  } catch (e: any) { alert('Fehler: ' + e.message) }
}

async function markPaid(id: string) {
  try {
    await api.put(`/billing/invoices/${id}/pay`, { payment_method: 'Überweisung' })
    await loadData()
  } catch (e: any) { alert('Fehler: ' + e.message) }
}

function statusBadge(s: string) {
  const map: Record<string, any> = {
    draft: { text: 'Entwurf', class: 'bg-gray-100 text-gray-700' },
    sent: { text: 'Gesendet', class: 'bg-blue-100 text-blue-700' },
    paid: { text: 'Bezahlt', class: 'bg-green-100 text-green-700' },
    overdue: { text: 'Überfällig', class: 'bg-red-100 text-red-700' },
    cancelled: { text: 'Storniert', class: 'bg-gray-100 text-gray-700' }
  }
  return map[s] || { text: s, class: 'bg-gray-100' }
}

function formatCurrency(n: number): string {
  return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(n || 0)
}
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-2xl font-bold">💰 Abrechnung</h1>
        <p class="text-gray-500">Rechnungen & Sätze</p>
      </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-4 gap-4 mb-6">
      <div class="bg-white rounded-lg shadow p-4">
        <p class="text-sm text-gray-500">Offene Rechnungen</p>
        <p class="text-2xl font-bold text-blue-600">{{ stats.open_invoices || 0 }}</p>
        <p class="text-sm text-gray-500">{{ formatCurrency(stats.open_amount) }}</p>
      </div>
      <div class="bg-white rounded-lg shadow p-4">
        <p class="text-sm text-gray-500">Überfällig</p>
        <p class="text-2xl font-bold text-red-600">{{ stats.overdue_invoices || 0 }}</p>
        <p class="text-sm text-gray-500">{{ formatCurrency(stats.overdue_amount) }}</p>
      </div>
      <div class="bg-white rounded-lg shadow p-4">
        <p class="text-sm text-gray-500">Bezahlt (30 Tage)</p>
        <p class="text-2xl font-bold text-green-600">{{ formatCurrency(stats.paid_last_30_days) }}</p>
      </div>
      <div class="bg-white rounded-lg shadow p-4">
        <p class="text-sm text-gray-500">Stundensätze</p>
        <p class="text-2xl font-bold">{{ rates.length }}</p>
      </div>
    </div>

    <!-- Tabs -->
    <div class="flex space-x-1 border-b mb-6">
      <button @click="activeTab = 'invoices'" 
              :class="['px-4 py-2 font-medium border-b-2 -mb-px', activeTab === 'invoices' ? 'border-blue-600 text-blue-600' : 'border-transparent']">
        Rechnungen
      </button>
      <button @click="activeTab = 'rates'" 
              :class="['px-4 py-2 font-medium border-b-2 -mb-px', activeTab === 'rates' ? 'border-blue-600 text-blue-600' : 'border-transparent']">
        Stundensätze
      </button>
    </div>

    <div v-if="loading" class="text-center py-12">Laden...</div>

    <!-- Invoices -->
    <div v-else-if="activeTab === 'invoices'">
      <div v-if="invoices.length === 0" class="bg-gray-50 rounded-lg p-12 text-center text-gray-500">
        <p class="text-4xl mb-4">📄</p>
        <p>Keine Rechnungen vorhanden</p>
      </div>

      <div v-else class="bg-white rounded-lg shadow overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nr.</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kunde</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Datum</th>
              <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Betrag</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
              <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Aktionen</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200">
            <tr v-for="inv in invoices" :key="inv.id" class="hover:bg-gray-50">
              <td class="px-4 py-3 text-sm font-medium">{{ inv.invoice_number }}</td>
              <td class="px-4 py-3 text-sm">{{ inv.customer_name }}</td>
              <td class="px-4 py-3 text-sm">{{ new Date(inv.invoice_date).toLocaleDateString('de-DE') }}</td>
              <td class="px-4 py-3 text-sm text-right font-semibold">{{ formatCurrency(inv.total) }}</td>
              <td class="px-4 py-3">
                <span :class="['px-2 py-1 text-xs rounded', statusBadge(inv.status).class]">
                  {{ statusBadge(inv.status).text }}
                </span>
              </td>
              <td class="px-4 py-3 text-right text-sm space-x-2">
                <button v-if="inv.status === 'draft'" @click="sendInvoice(inv.id)" class="text-blue-600 hover:underline">Senden</button>
                <button v-if="inv.status === 'sent' || inv.status === 'overdue'" @click="markPaid(inv.id)" class="text-green-600 hover:underline">Bezahlt</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Rates -->
    <div v-else-if="activeTab === 'rates'">
      <div v-if="rates.length === 0" class="bg-gray-50 rounded-lg p-12 text-center text-gray-500">
        <p class="text-4xl mb-4">💵</p>
        <p>Keine Stundensätze definiert</p>
      </div>

      <div v-else class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div v-for="r in rates" :key="r.id" class="bg-white rounded-lg shadow p-4">
          <div class="flex justify-between items-start">
            <div>
              <h3 class="font-semibold">{{ r.name }}</h3>
              <p class="text-sm text-gray-500">{{ r.customer_name || 'Allgemein' }}</p>
            </div>
            <span v-if="r.is_default" class="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded">Standard</span>
          </div>
          <p class="text-2xl font-bold mt-2">{{ formatCurrency(r.amount) }}</p>
          <p class="text-sm text-gray-500">pro {{ r.rate_type === 'hourly' ? 'Stunde' : r.rate_type === 'daily' ? 'Tag' : 'Monat' }}</p>
        </div>
      </div>
    </div>
  </div>
</template>
