<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import UpLink from "./display/UpLink.svelte";
  import { Component, UNTYPED, UpType, Widget } from "../lib/types";
  import Table from "./widgets/Table.svelte";
  import TableComponent from "./widgets/Table.svelte"; // silence false svelte(reactive-component) warnings
  import type { UpEntry } from "upend";
  import Icon from "./utils/Icon.svelte";
  import IconButton from "./utils/IconButton.svelte";

  export let entries: UpEntry[];
  export let type: UpType | undefined = undefined;
  export let title: String | undefined = undefined;
  export let editable = false;
  export let reverse = false;

  let currentWidget: string | undefined;

  let availableWidgets: Widget[] = [];
  $: {
    availableWidgets = [
  {
        name: "table",
        icon: "table",
        components: [
          {
            component: TableComponent,
          },
        ],
      },
    ];

    if (type?.widgetInfo) {
      availableWidgets = [type.widgetInfo, ...availableWidgets];
    }
    currentWidget = availableWidgets[0].name;
  }

  let components: Component[] = [];
  $: {
    components = availableWidgets.find(
      (w) => w.name === currentWidget
    )!.components;
  }
</script>

<section class="attribute-view labelborder">
  <header>
    <h3>
      {#if type && type !== UNTYPED}
        <UpLink to={{ entity: type.address }}>
          {#if type.icon}
            <div class="icon">
              <Icon name={type.icon} />
            </div>
          {/if}
          {type.name || "???"}
        </UpLink>
      {:else}
        {title || "???"}
      {/if}
    </h3>

    {#if currentWidget && (availableWidgets.length > 1 || editable)}
      <div class="views">
        {#each availableWidgets as widget (widget.name)}
          <IconButton
            name={widget.icon || "question-diamond"}
            active={widget.name === currentWidget}
            --active-color="var(--foreground)"
            on:click={() => (currentWidget = widget.name)}
          />
        {/each}
      </div>
    {/if}
  </header>
  {#if !reverse}
    {#each components as component}
      <svelte:component
        this={component.component}
        {...component.props || {}}
        {entries}
        {editable}
        on:change
      />
    {/each}
  {:else}
    <Table columns="entity, attribute" {entries} />
  {/if}
</section>

<style scoped lang="scss">
  @use "./util";

  .icon {
    display: inline-block;
    font-size: 1.25em;
    margin-top: -0.3em;
    position: relative;
    bottom: -2px;
  }

  .views {
    display: flex;
    right: 1ex;
    font-size: 18px;
  }
</style>
