<!-- src/lib/components/AnmeldungenTable.svelte -->
<script lang="ts">
  import { createEventDispatcher } from 'svelte';

  export let anmeldungen: any[];
  export let getStatusColor: (status: string) => string;
  export let getStatusText: (status: string) => string;

  const dispatch = createEventDispatcher<{
    accept: { id: number };
    reject: { id: number };
    delete: { id: number };
  }>();

  function formatDate(timestamp: number): string {
    return new Date(timestamp).toLocaleDateString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  function formatGeburtsdatum(dateString: string | undefined): string {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleDateString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
  }

  function formatProcessedDate(timestamp: number | undefined): string {
    if (!timestamp) return '-';
    return new Date(timestamp).toLocaleDateString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  function formatZeitraum(zeitraum: any): string {
    if (!zeitraum) return '-';
    const start = new Date(zeitraum.startDatum).toLocaleDateString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
    const end = new Date(zeitraum.endDatum).toLocaleDateString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
    return `${zeitraum.bezeichnung} (${start} - ${end})`;
  }

  // Schulart formatieren
  function formatSchulart(schulart: string | undefined): string {
    if (!schulart) return '-';
    const mapping: Record<string, string> = {
      'Gymnasium': 'Gymnasium',
      'KGS_Gymnasialzweig': 'KGS Gymnasialzweig',
      'Fachoberschule': 'Fachoberschule',
      'Realschule': 'Realschule',
      'KGSR': 'KGS Realschulzweig',
      'IGSR': 'IGS Realschulzweig'
    };
    return mapping[schulart] || schulart;
  }

  // Sozialverhalten kürzen
  function formatSozialverhalten(sv: string | undefined): string {
    if (!sv) return '-';
    if (sv === 'Entspricht den Erwartungen in vollem Umfang') return 'Voll entspr.';
    if (sv === 'Entspricht den Erwartungen') return 'Entsprechend';
    if (sv === 'Entspricht den Erwartungen mit Einschränkungen') return 'Mit Einschr.';
    return sv;
  }

  function canBeAccepted(status: string): boolean {
    return status === 'pending';
  }

  function canBeRejected(status: string): boolean {
    return status === 'pending';
  }
</script>

<div class="overflow-x-auto">
  <table class="min-w-full divide-y divide-gray-200">
    <thead class="bg-gray-50">
    <tr>
      <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
        Status
      </th>
      <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
        Persönliche Daten
      </th>
      <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
        Kontakt & Adresse
      </th>
      <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
        Schule & Noten
      </th>
      <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
        Praktikum & Wünsche
      </th>
      <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
        Dokumente
      </th>
      <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
        Aktionen
      </th>
    </tr>
    </thead>
    <tbody class="bg-white divide-y divide-gray-200">
    {#each anmeldungen as anmeldung (anmeldung.id)}
      <tr class="hover:bg-gray-50 align-top">
        <!-- Status -->
        <td class="px-3 py-4">
            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {getStatusColor(anmeldung.status || 'pending')}">
              {getStatusText(anmeldung.status || 'pending')}
            </span>
          <div class="text-xs text-gray-400 mt-2">
            Eingang:<br>
            {formatDate(anmeldung.timestamp)}
          </div>
        </td>

        <!-- Persönliche Daten -->
        <td class="px-3 py-4">
          <div class="text-sm font-medium text-gray-900">
            {anmeldung.anrede} {anmeldung.vorname} {anmeldung.nachname}
          </div>
          <div class="text-xs text-gray-500 mt-1">
            <span class="font-medium">Geb.:</span> {formatGeburtsdatum(anmeldung.geburtsdatum)}
          </div>
          {#if anmeldung.alter}
            <div class="text-xs text-gray-500">
              <span class="font-medium">Alter:</span> {anmeldung.alter} Jahre
            </div>
          {/if}
        </td>

        <!-- Kontakt & Adresse -->
        <td class="px-3 py-4 text-sm">
          <div class="text-xs space-y-1">
            <div>
              <span class="font-medium text-gray-700">Adresse:</span><br>
              <span class="text-gray-600">
                  {anmeldung.strasse || '-'} {anmeldung.hausnummer || ''}<br>
                {anmeldung.plz || ''} {anmeldung.ort || ''}
                </span>
            </div>
            <div>
              <span class="font-medium text-gray-700">Tel:</span>
              {#if anmeldung.telefon}
                <a href="tel:{anmeldung.telefon}" class="text-blue-600 hover:text-blue-800">{anmeldung.telefon}</a>
              {:else}
                <span class="text-gray-400">-</span>
              {/if}
            </div>
            <div>
              <span class="font-medium text-gray-700">E-Mail:</span><br>
              <a href="mailto:{anmeldung.email}" class="text-blue-600 hover:text-blue-800 break-all text-xs">{anmeldung.email}</a>
            </div>

            <!-- Notfallkontakt -->
            {#if anmeldung.notfallVorname || anmeldung.notfallNachname || anmeldung.notfallTelefon}
              <div class="mt-2 pt-2 border-t border-gray-100">
                <span class="font-medium text-orange-700">Notfallkontakt:</span>
                <div class="text-gray-600">
                  {anmeldung.notfallVorname || ''} {anmeldung.notfallNachname || ''}
                </div>
                {#if anmeldung.notfallTelefon}
                  <a href="tel:{anmeldung.notfallTelefon}" class="text-blue-600 hover:text-blue-800">
                    {anmeldung.notfallTelefon}
                  </a>
                {/if}
              </div>
            {/if}
          </div>
        </td>

        <!-- Schule & Noten -->
        <td class="px-3 py-4 text-sm">
          <div class="text-xs space-y-1">
            <div>
              <span class="font-medium text-gray-700">Schulart:</span><br>
              <span class="text-gray-900">{formatSchulart(anmeldung.schulart)}</span>
            </div>
            {#if anmeldung.schulklasse}
              <div>
                <span class="font-medium text-gray-700">Klasse:</span>
                <span class="text-gray-900">{anmeldung.schulklasse}. Klasse</span>
              </div>
            {/if}
            <div class="pt-1 border-t border-gray-100">
              <span class="font-medium text-gray-700">Noten:</span>
              <div class="flex gap-2 mt-1">
                  <span class="inline-flex items-center px-2 py-0.5 rounded text-xs bg-gray-100">
                    D: <span class="font-bold ml-1">{anmeldung.noteDeutsch || '-'}</span>
                  </span>
                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs bg-gray-100">
                    M: <span class="font-bold ml-1">{anmeldung.noteMathe || '-'}</span>
                  </span>
              </div>
            </div>
            {#if anmeldung.sozialverhalten}
              <div>
                <span class="font-medium text-gray-700">Sozialverh.:</span>
                <span class="text-gray-900 text-xs">{formatSozialverhalten(anmeldung.sozialverhalten)}</span>
              </div>
            {/if}
          </div>
        </td>

        <!-- Praktikum & Wünsche -->
        <td class="px-3 py-4 text-sm">
          <div class="text-xs space-y-2">
            <!-- Zeitraum -->
            {#if anmeldung.zeitraum}
              <div>
                <span class="font-medium text-gray-700">Zeitraum:</span><br>
                <span class="text-gray-900">{formatZeitraum(anmeldung.zeitraum)}</span>
              </div>
            {/if}

            <!-- Zugewiesene Dienststelle -->
            {#if anmeldung.assignedDienststelle}
              <div class="p-2 bg-green-50 border border-green-200 rounded">
                <div class="flex items-center text-green-700">
                  <svg class="w-4 h-4 mr-1 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                  </svg>
                  <span class="font-semibold">Zugewiesen:</span>
                </div>
                <div class="text-green-800 mt-1">{anmeldung.assignedDienststelle.name}</div>
                {#if anmeldung.processedAt}
                  <div class="text-xs text-green-600 mt-1">
                    {formatProcessedDate(anmeldung.processedAt)}
                  </div>
                {/if}
              </div>
            {/if}

            <!-- Alle 3 Wünsche -->
            <div>
              <span class="font-medium text-gray-700">Wünsche:</span>
              <div class="space-y-1 mt-1">
                {#if anmeldung.wunsch1}
                  <div class="flex items-start">
                    <span class="inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-white bg-blue-600 rounded-full mr-1 flex-shrink-0">1</span>
                    <span class="text-gray-900 leading-tight">{anmeldung.wunsch1.name}</span>
                  </div>
                {/if}
                {#if anmeldung.wunsch2}
                  <div class="flex items-start">
                    <span class="inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-white bg-blue-500 rounded-full mr-1 flex-shrink-0">2</span>
                    <span class="text-gray-900 leading-tight">{anmeldung.wunsch2.name}</span>
                  </div>
                {/if}
                {#if anmeldung.wunsch3}
                  <div class="flex items-start">
                    <span class="inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-white bg-blue-400 rounded-full mr-1 flex-shrink-0">3</span>
                    <span class="text-gray-900 leading-tight">{anmeldung.wunsch3.name}</span>
                  </div>
                {/if}
                {#if !anmeldung.wunsch1 && !anmeldung.wunsch2 && !anmeldung.wunsch3}
                  <span class="text-gray-400">Keine Wünsche</span>
                {/if}
              </div>
            </div>

            <!-- Motivation -->
            {#if anmeldung.motivation}
              <div>
                <span class="font-medium text-gray-700">Motivation:</span>
                <p class="text-gray-600 mt-1 text-xs whitespace-pre-wrap line-clamp-3">{anmeldung.motivation}</p>
              </div>
            {/if}
          </div>
        </td>

        <!-- Dokumente / PDFs -->
        <td class="px-3 py-4">
          {#if anmeldung.pdfs && anmeldung.pdfs.length > 0}
            <div class="space-y-1">
              {#each anmeldung.pdfs as pdf, index}
                <a
                        href="/api/admin/pdf?path={encodeURIComponent(pdf.pfad)}"
                        target="_blank"
                        class="flex items-center text-xs text-blue-600 hover:text-blue-800 hover:bg-blue-50 p-1 rounded"
                >
                  <svg class="w-4 h-4 mr-1 text-red-500 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clip-rule="evenodd" />
                  </svg>
                  PDF {index + 1}
                  <svg class="w-3 h-3 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                </a>
              {/each}
            </div>
          {:else}
            <span class="text-xs text-gray-400">Keine Dokumente</span>
          {/if}
        </td>

        <!-- Aktionen -->
        <td class="px-3 py-4">
          <div class="flex flex-col space-y-2">
            {#if canBeAccepted(anmeldung.status || 'pending')}
              <button
                      on:click={() => dispatch('accept', { id: anmeldung.id })}
                      class="text-green-600 hover:text-green-900 px-3 py-1.5 rounded text-xs font-medium border border-green-300 hover:bg-green-50 text-center whitespace-nowrap"
              >
                ✓ Annehmen
              </button>
            {/if}

            {#if canBeRejected(anmeldung.status || 'pending')}
              <button
                      on:click={() => dispatch('reject', { id: anmeldung.id })}
                      class="text-red-600 hover:text-red-900 px-3 py-1.5 rounded text-xs font-medium border border-red-300 hover:bg-red-50 text-center whitespace-nowrap"
              >
                ✗ Ablehnen
              </button>
            {/if}

            <button
                    on:click={() => dispatch('delete', { id: anmeldung.id })}
                    class="text-gray-600 hover:text-gray-900 px-3 py-1.5 rounded text-xs font-medium border border-gray-300 hover:bg-gray-50 text-center whitespace-nowrap"
            >
              🗑 Löschen
            </button>
          </div>
        </td>
      </tr>
    {/each}
    </tbody>
  </table>
</div>

<style>
  .line-clamp-3 {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>