<script lang="ts">
  import BasicDropdown from "./basic-dropdown.webc.svelte";
  import { type FieldInfo } from "./field.svelte";
  import FieldDetails from "./field-details.svelte";

  type Props = {
    field: FieldInfo;
    index: number;
    ondragenter?(ev: DragEvent): unknown;
    ondragleave?(ev: DragEvent): unknown;
    ondragover?(ev: DragEvent): unknown;
    ondragstart?(ev: DragEvent): unknown;
    ondrop?(ev: DragEvent): unknown;
  };

  let {
    field = $bindable(),
    index,
    ondragenter,
    ondragleave,
    ondragover,
    ondragstart,
    ondrop,
  }: Props = $props();

  const original_label_value = field.field.table_label;

  let type_indicator_element = $state<HTMLButtonElement | undefined>();
  let name_value = $state(field.field.name);
  let label_value = $state(field.field.table_label ?? "");

  $effect(() => {
    field.field.table_label = label_value === "" ? undefined : label_value;
  });
</script>

<div
  aria-colindex={index}
  class="field-header__container"
  draggable={true}
  {ondragenter}
  {ondragleave}
  {ondragover}
  {ondragstart}
  {ondrop}
  role="columnheader"
  style:width={`${field.field.table_width_px}px`}
  tabindex={0}
>
  <div class="field-header__label">
    {field.field.table_label ?? field.field.name}
  </div>
  <div class="field-header__menu-container">
    <BasicDropdown
      alignment="right"
      button_class="field-header__type-indicator"
      on_toggle={(ev) => {
        if (ev.newState === "closed") {
          type_indicator_element?.focus();
          field.field.table_label = original_label_value;
          label_value = original_label_value ?? "";
        }
      }}
    >
      <span slot="button-contents">
        {#if field.field.presentation.t === "Dropdown"}
          <i class="ti ti-pointer"></i>
        {:else if field.field.presentation.t === "Text"}
          <i class="ti ti-file-text"></i>
        {:else if field.field.presentation.t === "Timestamp"}
          <i class="ti ti-calendar"></i>
        {:else if field.field.presentation.t === "Uuid"}
          <i class="ti ti-id"></i>
        {/if}
      </span>
      <div slot="popover" style:padding="16px">
        <form method="post" action="update-field">
          <FieldDetails
            bind:name_value
            bind:label_value
            name_input_disabled
            presentation={field.field.presentation}
          />
          <input type="hidden" name="field_id" value={field.field.id} />
          <button class="button--primary" type="submit">Save</button>
        </form>
      </div>
    </BasicDropdown>
  </div>
</div>
