<script>
  import { Button, Select } from "@budibase/bbui"
  import { tables, views } from "stores/backend"
  import { notifications } from "@budibase/bbui"
  import { FIELDS } from "constants/backend"

  export let view = {}
  export let onClosed

  $: viewTable = $tables.list.find(({ _id }) => _id === $views.selected.tableId)
  $: fields =
    viewTable &&
    Object.entries(viewTable.schema)
      .filter(entry => entry[1].type !== FIELDS.LINK.type)
      .map(([key]) => key)

  function saveView() {
    views.save(view)
    notifications.success(`View ${view.name} saved.`)
    onClosed()
  }
</script>

<div class="actions">
  <h5>Group By</h5>
  <Select bind:value={view.groupBy} options={fields} />
  <div class="footer">
    <Button secondary on:click={onClosed}>Cancel</Button>
    <Button cta on:click={saveView}>Save</Button>
  </div>
</div>

<style>
  .actions {
    display: grid;
    width: 200px;
    grid-gap: var(--spacing-xl);
    padding: var(--spacing-xl);
  }

  h5 {
    margin: 0;
    font-weight: 500;
  }

  .footer {
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-m);
  }

  .input-group-row {
    display: grid;
    grid-template-columns: 20px 1fr;
    gap: var(--spacing-s);
    align-items: center;
  }

  p {
    margin: 0;
    font-size: var(--font-size-xs);
  }
</style>
