<script lang="ts">
  import { browser } from '$app/environment';
  import { goto } from '$app/navigation';
  import { onMount, onDestroy } from 'svelte';
  import { isAuthenticated, getTrunks, createTrunk, updateTrunk, deleteTrunk, connectWebSocket, type Trunk } from '$lib/api';
  import { toast } from 'svelte-sonner';
  import { Plus, Trash2, Save, X, Cable } from 'lucide-svelte';

  let trunks: Trunk[] = [];
  let loading = true;

  // Gateway статусы с ESLa (up/down/unknown)
  let ws: WebSocket | null = null;
  let gatewayStatuses: Record<string, string> = {};

  // Edit mode
  let editing: string | null = null; // trunk ID being edited
  let editData: Partial<Trunk> = {};
  let creating = false;
  let newData: Partial<Trunk> = {
    type: 'balance',
    enabled: true,
    codecs: ['PCMU', 'PCMA'],
    context: 'default',
  };

  let typeFilter = '';

  if (browser && !isAuthenticated()) { goto('/login'); }

  onMount(() => {
    loadTrunks();
    ws = connectWebSocket((msg) => {
      if (msg.type === 'gateway_update') {
        const { trunk_id, status } = msg.payload;
        gatewayStatuses = { ...gatewayStatuses, [trunk_id]: status };
      }
    });
  });

  onDestroy(() => {
    ws?.close();
  });

  async function loadTrunks() {
    loading = true;
    try {
      trunks = await getTrunks(typeFilter || undefined);
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      loading = false;
    }
  }

  function startEdit(t: Trunk) {
    editing = t.id;
    editData = { ...t };
  }

  function cancelEdit() {
    editing = null;
    creating = false;
    editData = {};
  }

  async function saveEdit() {
    if (!editing) return;
    try {
      const updated = await updateTrunk(editing, editData);
      const idx = trunks.findIndex(t => t.id === editing);
      if (idx >= 0) trunks[idx] = updated;
      editing = null;
      toast.success('Транк обновлён');
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  async function saveCreate() {
    try {
      const created = await createTrunk(newData);
      trunks = [...trunks, created];
      creating = false;
      newData = { type: 'balance', enabled: true, codecs: ['PCMU', 'PCMA'], context: 'default' };
      toast.success('Транк создан');
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  async function removeTrunk(id: string) {
    if (!confirm('Удалить транк?')) return;
    try {
      await deleteTrunk(id);
      trunks = trunks.filter(t => t.id !== id);
      toast.success('Транк удалён');
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  function typeBadge(type: string): string {
    switch (type) {
      case 'ingress': return 'bg-blue-100 text-blue-700';
      case 'balance': return 'bg-green-100 text-green-700';
      case 'fallback': return 'bg-orange-100 text-orange-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  }

  function typeLabel(type: string): string {
    switch (type) {
      case 'ingress': return 'Вход';
      case 'balance': return 'Баланс';
      case 'fallback': return 'Резерв';
      default: return type;
    }
  }

  function gatewayIndicator(trunkID: string): string {
    const s = gatewayStatuses[trunkID] || 'unknown';
    if (s === 'up') return '🟢';
    if (s === 'down') return '🔴';
    return '⚪';
  }

  function onFilterChange(e: Event) {
    typeFilter = (e.target as HTMLSelectElement).value;
    loadTrunks();
  }
</script>

<div class="space-y-6">
  <div class="flex items-center justify-between">
    <h1 class="text-xl font-bold flex items-center gap-2">
      <Cable class="h-5 w-5" /> Транки
    </h1>
    <button on:click={() => (creating = true)} class="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90">
      <Plus class="h-4 w-4" /> Создать
    </button>
  </div>

  <!-- Filter -->
  <div class="flex items-center gap-4">
    <select value={typeFilter} on:change={onFilterChange} class="px-3 py-2 border rounded-md text-sm bg-background">
      <option value="">Все типы</option>
      <option value="ingress">Ingress (входные)</option>
      <option value="balance">Balance (балансировка)</option>
      <option value="fallback">Fallback (резерв)</option>
    </select>
  </div>

  <!-- Create form -->
  {#if creating}
    <div class="border rounded-lg p-4 bg-yellow-50 border-yellow-200">
      <h3 class="text-sm font-semibold mb-3">Новый транк</h3>
      <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-3">
        <input class="px-3 py-2 border rounded-md text-sm" placeholder="Название" bind:value={newData.name} />
        <select class="px-3 py-2 border rounded-md text-sm bg-background" bind:value={newData.type}>
          <option value="ingress">Ingress</option>
          <option value="balance">Balance</option>
          <option value="fallback">Fallback</option>
        </select>
        <input class="px-3 py-2 border rounded-md text-sm" placeholder="Gateway (sip:...)" bind:value={newData.gateway} />
      </div>
      <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-3">
        <input class="px-3 py-2 border rounded-md text-sm" placeholder="Node ID (для balance)" bind:value={newData.node_id} />
        <input class="px-3 py-2 border rounded-md text-sm" placeholder="Context" bind:value={newData.context} />
      </div>
      <div class="flex items-center gap-3 mb-3">
        <label class="flex items-center gap-2 text-sm">
          <input type="checkbox" bind:checked={newData.enabled} class="rounded" /> Включён
        </label>
        <input class="flex-1 px-3 py-2 border rounded-md text-sm" placeholder="Описание" bind:value={newData.description} />
      </div>
      <div class="flex gap-2">
        <button on:click={saveCreate} class="flex items-center gap-1 px-3 py-2 bg-primary text-primary-foreground rounded-md text-sm"><Save class="h-3 w-3" /> Создать</button>
        <button on:click={cancelEdit} class="flex items-center gap-1 px-3 py-2 border rounded-md text-sm"><X class="h-3 w-3" /> Отмена</button>
      </div>
    </div>
  {/if}

  {#if loading}
    <p class="text-muted-foreground text-sm">Загрузка...</p>
  {:else if trunks.length === 0}
    <p class="text-muted-foreground text-sm py-8 text-center">Нет транков. Создайте первый.</p>
  {:else}
    <div class="border rounded-lg overflow-hidden">
      <table class="w-full text-sm">
        <thead class="bg-secondary">
          <tr>
            <th class="px-4 py-3 text-left font-medium">Название</th>
            <th class="px-4 py-3 text-left font-medium">Тип</th>
            <th class="px-4 py-3 text-left font-medium">Gateway</th>
            <th class="px-4 py-3 text-left font-medium">Node ID</th>
            <th class="px-4 py-3 text-left font-medium">Статус</th>
            <th class="px-4 py-3 text-right font-medium">Действия</th>
          </tr>
        </thead>
        <tbody>
          {#each trunks as t (t.id)}
            {#if editing === t.id}
              <!-- Edit row -->
              <tr class="border-t bg-yellow-50">
                <td class="px-4 py-2"><input class="w-full px-2 py-1 border rounded text-sm" bind:value={editData.name} /></td>
                <td class="px-4 py-2">
                  <select class="w-full px-2 py-1 border rounded text-sm" bind:value={editData.type}>
                    <option value="ingress">Ingress</option>
                    <option value="balance">Balance</option>
                    <option value="fallback">Fallback</option>
                  </select>
                </td>
                <td class="px-4 py-2"><input class="w-full px-2 py-1 border rounded text-sm" bind:value={editData.gateway} /></td>
                <td class="px-4 py-2"><input class="w-full px-2 py-1 border rounded text-sm" bind:value={editData.node_id} /></td>
                <td class="px-4 py-2">
                  <label class="flex items-center gap-2 text-sm">
                    <input type="checkbox" bind:checked={editData.enabled} />
                    {editData.enabled ? 'Вкл' : 'Выкл'}
                  </label>
                </td>
                <td class="px-4 py-2 text-right">
                  <div class="flex gap-1 justify-end">
                    <button on:click={saveEdit} class="px-2 py-1 bg-primary text-primary-foreground rounded text-xs"><Save class="h-3 w-3 inline" /></button>
                    <button on:click={cancelEdit} class="px-2 py-1 border rounded text-xs"><X class="h-3 w-3 inline" /></button>
                  </div>
                </td>
              </tr>
            {:else}
              <!-- Normal row -->
              <tr class="border-t hover:bg-secondary/50">
                <td class="px-4 py-3 font-medium">{t.name}</td>
                <td class="px-4 py-3"><span class="px-2 py-1 rounded text-xs font-medium {typeBadge(t.type)}">{typeLabel(t.type)}</span></td>
                 <td class="px-4 py-3 font-mono text-xs">
                  {t.gateway}
                  {#if t.type === 'ingress'}
                    <span class="ml-2" title="Gateway: {gatewayStatuses[t.id] || 'unknown'}">{gatewayIndicator(t.id)}</span>
                  {/if}
                <td class="px-4 py-3 font-mono text-xs">{t.node_id || '—'}</td>
                <td class="px-4 py-3">{t.enabled ? '🟢 Вкл' : '🔴 Выкл'}</td>
                <td class="px-4 py-3 text-right">
                  <button on:click={() => startEdit(t)} class="px-2 py-1 text-xs text-primary hover:underline mr-1">Изменить</button>
                  <button on:click={() => removeTrunk(t.id)} class="px-2 py-1 text-xs text-destructive hover:underline"><Trash2 class="h-3 w-3 inline" /></button>
                </td>
              </tr>
            {/if}
          {/each}
        </tbody>
      </table>
    </div>
  {/if}
</div>
