<script lang="ts">
  import { browser } from '$app/environment';
  import { goto } from '$app/navigation';
  import { onMount, onDestroy } from 'svelte';
  import { isAuthenticated, getNodes, toggleNode, connectWebSocket, type NodeInfo } from '$lib/api';
  import { toast } from 'svelte-sonner';
  import { Phone, Power, PowerOff } from 'lucide-svelte';

  let nodes: NodeInfo[] = [];
  let ws: WebSocket | null = null;
  let loading = true;

  // Toggle dialog
  let toggleTarget: string | null = null;
  let toggleDisabling = false;
  let toggleReason = '';

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

  onMount(() => {
    loadNodes();
    ws = connectWebSocket((msg) => {
      if (msg.type === 'nodes_update') {
        nodes = msg.payload;
      }
    });
  });

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

  async function loadNodes() {
    try {
      nodes = await getNodes();
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      loading = false;
    }
  }

  function openToggle(nodeId: string, currentlyDisabled: boolean) {
    toggleTarget = nodeId;
    toggleDisabling = !currentlyDisabled;
    toggleReason = '';
  }

  async function confirmToggle() {
    if (!toggleTarget) return;
    try {
      const updated = await toggleNode(toggleTarget, toggleDisabling, toggleReason);
      const idx = nodes.findIndex(n => n.node_id === toggleTarget);
      if (idx >= 0) nodes[idx] = updated;
      toast.success(toggleDisabling ? `Нода ${toggleTarget} исключена из распределения` : `Нода ${toggleTarget} возвращена в распределение`);
      toggleTarget = null;
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  function scoreColor(score: number): string {
    if (score >= 70) return 'text-green-600';
    if (score >= 40) return 'text-yellow-600';
    if (score >= 0) return 'text-orange-600';
    return 'text-red-600';
  }
</script>

<div class="space-y-6">
  <h1 class="text-xl font-bold flex items-center gap-2">
    <Phone class="h-5 w-5" /> Ноды
  </h1>

  {#if loading}
    <p class="text-muted-foreground text-sm">Загрузка...</p>
  {:else if nodes.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">Node ID</th>
            <th class="px-4 py-3 text-left font-medium">Score</th>
            <th class="px-4 py-3 text-left font-medium">Звонки</th>
            <th class="px-4 py-3 text-left font-medium">CPU idle</th>
            <th class="px-4 py-3 text-left font-medium">Load</th>
            <th class="px-4 py-3 text-left font-medium">Fail %</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 nodes as n (n.node_id)}
            <tr class="border-t hover:bg-secondary/50">
              <td class="px-4 py-3 font-mono font-medium">{n.node_id}</td>
              <td class="px-4 py-3 font-mono font-bold {scoreColor(n.score)}">{n.score.toFixed(0)}</td>
              <td class="px-4 py-3 font-mono">{n.active_calls}/{n.max_calls}</td>
              <td class="px-4 py-3 font-mono">{n.idle_cpu.toFixed(0)}%</td>
              <td class="px-4 py-3 font-mono">{n.load_avg.toFixed(2)}</td>
              <td class="px-4 py-3 font-mono">{n.call_failure_rate.toFixed(1)}%</td>
              <td class="px-4 py-3">
                {#if n.disabled}
                  <span class="text-red-600 font-medium">disabled</span>
                {:else if n.is_stale}
                  <span class="text-red-600 font-medium">stale</span>
                {:else if n.score < 0}
                  <span class="text-red-600 font-medium">{n.lethal_reason || 'unhealthy'}</span>
                {:else}
                  <span class="text-green-600 font-medium">healthy</span>
                {/if}
                <div class="text-xs text-muted-foreground">{n.seconds_ago.toFixed(0)}с назад</div>
              </td>
              <td class="px-4 py-3 text-right">
                {#if n.disabled}
                  <button on:click={() => openToggle(n.node_id, true)} class="flex items-center gap-1 px-3 py-1.5 bg-green-600 text-white rounded text-xs hover:opacity-90">
                    <Power class="h-3 w-3" /> Вернуть
                  </button>
                {:else}
                  <button on:click={() => openToggle(n.node_id, false)} class="flex items-center gap-1 px-3 py-1.5 bg-red-600 text-white rounded text-xs hover:opacity-90">
                    <PowerOff class="h-3 w-3" /> Исключить
                  </button>
                {/if}
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  {/if}

  <!-- Toggle confirmation dialog -->
  {#if toggleTarget}
    <div class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" on:click={() => (toggleTarget = null)} on:keydown={(e) => { if (e.key === 'Escape') toggleTarget = null; }} role="dialog">
      <div class="bg-card border rounded-lg p-6 w-full max-w-md shadow-lg" on:click|stopPropagation>
        <h3 class="text-lg font-semibold mb-2">
          {toggleDisabling ? 'Исключить ноду из распределения?' : 'Вернуть ноду в распределение?'}
        </h3>
        <p class="text-sm text-muted-foreground mb-4">
          Нода: <span class="font-mono font-medium">{toggleTarget}</span>
        </p>

        {#if toggleDisabling}
          <div class="mb-4">
            <label for="reason" class="block text-sm font-medium mb-1">Причина исключения</label>
            <input
              id="reason"
              type="text"
              bind:value={toggleReason}
              class="w-full px-3 py-2 border rounded-md text-sm bg-background"
              placeholder="Например: технические работы"
            />
          </div>
        {/if}

        <div class="flex gap-2 justify-end">
          <button on:click={() => (toggleTarget = null)} class="px-4 py-2 border rounded-md text-sm">Отмена</button>
          <button on:click={confirmToggle} class="px-4 py-2 {toggleDisabling ? 'bg-destructive text-destructive-foreground' : 'bg-primary text-primary-foreground'} rounded-md text-sm font-medium">
            {toggleDisabling ? 'Исключить' : 'Вернуть'}
          </button>
        </div>
      </div>
    </div>
  {/if}
</div>
