<script lang="ts">
  import Table from "./lib/Table.svelte";
  import NewsForm from "./lib/NewsForm.svelte";
  import { fetchData } from "./lib/RestAPI.svelte.ts";
  import type { Retailer } from "./lib/Models.svelte.ts";

  let retailerrecords: Retailer[] = $state([]);

  let activeTab = $state("invoice");

  $effect(() => {
    if (activeTab === "retailers") {
      fetchData("retailers/", retailerrecords);
    }
  });

  let showModal = $state(false);

  function openModal() {
    showModal = true;
  }

  function removeRowHandler(id: Number) {
    console.log("Remove Record:", id);
  }
</script>

<!-- Bootstrap Modal -->
<div
  class="modal fade {showModal ? 'show' : ''}"
  tabindex="-1"
  role="dialog"
  style="display: {showModal ? 'block' : 'none'};"
>
  <NewsForm {showModal} role={"edit"} />
</div>

<main>
  <ul class="nav nav-tabs">
    <li class="nav-item">
      <a
        class="nav-link {activeTab === 'invoice' ? 'active' : ''}"
        href="#"
        onclick={() => (activeTab = "invoice")}>Invoices</a
      >
    </li>
    <li class="nav-item">
      <a
        class="nav-link {activeTab === 'retailers' ? 'active' : ''}"
        href="#"
        onclick={() => (activeTab = "retailers")}>Retailers</a
      >
    </li>
    <li class="nav-item">
      <a
        class="nav-link {activeTab === 'news' ? 'active' : ''}"
        href="#"
        onclick={() => (activeTab = "news")}>News</a
      >
    </li>
  </ul>

  <div class="container-fluid">
    {#if activeTab === "invoice"}
      <p>Invoice list</p>
    {/if}
    {#if activeTab === "retailers"}
      <div class="row justify-content-start">
        <div class="col-2 mt-3">
          <button
            onclick={openModal}
            type="button"
            class="btn btn-outline-primary">Add retailer</button
          >
        </div>
      </div>
      <div class="row">
        <div class="col">
          <Table {columns} {records} {removeRowHandler} />
        </div>
      </div>
    {/if}
    {#if activeTab === "news"}
      <p>news</p>
    {/if}
  </div>
</main>
