<script lang="ts">
  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.length > 0) {
      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}
          {#if type.name != "HIER"}
            {type.label || type.name || "???"}
          {:else}
            Members
          {/if}
        </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>
  <div class="content">
    {#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}
  </div>
</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>
