{{!
  Copyright (c) HashiCorp, Inc.
  SPDX-License-Identifier: BUSL-1.1
}}

<StateChart @src={{chart}} as |State Guard Action dispatch state|>

  <Ref @target={{this}} @name="dispatch" @value={{dispatch}} />

{{#let (hash
  data=data
  error=error
  persist=(action "persist")
  delete=(queue (action (mut data)) (action dispatch "REMOVE"))
  inflight=(state-matches state (array "persisting" "removing"))
  disabled=(state-matches state (array "persisting" "removing"))
) as |api|}}

  {{yield api}}

  <State @matches="removing">
    <DataSink
      @sink={{sink}}
      @item={{data}}
      @data={{null}}
      @onchange={{action dispatch "SUCCESS"}}
      @onerror={{action "error"}}
    />
  </State>

  <State @matches="persisting">
    <DataSink
      @sink={{sink}}
      @item={{data}}
      @onchange={{action dispatch "SUCCESS"}}
      @onerror={{action "error"}}
    />
  </State>

  <State @matches="removed">
{{#let
  (queue (action dispatch "RESET") (action ondelete))
as |after|}}
    {{#yield-slot name="removed" params=(block-params after)}}
      {{yield api}}
    {{else}}
      <Hds::Toast
        @color='success'
        {{notification
          after=(action after)
        }} as |T|>
        <T.Title>Success!</T.Title>
        <T.Description>Your {{or label type}} has been deleted.</T.Description>
      </Hds::Toast>
    {{/yield-slot}}
{{/let}}
  </State>

  <State @matches="persisted">
{{#let
  (action onchange)
as |after|}}
    {{#yield-slot name="persisted" params=(block-params after)}}
      {{yield api}}
    {{else}}
      <Hds::Toast
        @color='success'
        {{notification
          after=(action after)
        }} as |T|>
        <T.Title>Success!</T.Title>
        <T.Description>Your {{or label type}} has been saved.</T.Description>
      </Hds::Toast>
    {{/yield-slot}}
{{/let}}
  </State>

  <State @matches="error">
{{#let
  (action dispatch "RESET")
as |after|}}
    {{#yield-slot name="error" params=(block-params after api.error)}}
      {{yield api}}
    {{else}}
      <Hds::Toast
        @color='critical'
        {{notification
          after=(action after)
        }} as |T|>
        <T.Title>Error!</T.Title>
        <T.Description>There was an error saving your {{or label type}}.
          {{#if (and api.error.status api.error.detail)}}
            <br />{{api.error.status}}: {{api.error.detail}}
          {{else if api.error.message}}
            <br />{{api.error.message}}
          {{/if}}
        </T.Description>
      </Hds::Toast>
    {{/yield-slot}}
{{/let}}
  </State>

  <YieldSlot @name="content">
    {{yield api}}
  </YieldSlot>

{{/let}}
</StateChart>