<script lang="ts">
  import InputText from '../TextInput.svelte'
  import InputInt from '../IntInput.svelte'
  import InvertableButton from '../InvertableIconButton.svelte';

  export let text: string;
  export let todo: number = null;
  export let done: number = null;
  export let onInput: () => void;
  export let onBlur: () => void = () => {};

  let doEdit: boolean = false;
  
  function onClick() {
    doEdit = !doEdit;
  }
  
  function handleBlur() {
    doEdit = !doEdit;
    onBlur();
  }

  function saveEntry() {
    if (todo && !done) {
      done = 0;
    }
    onInput();
    doEdit = false;
  }

  function deleteEntry() {
    text = "";
    todo = null;
    done = null;
    onInput();
    doEdit = false;
  }
</script>

{#if doEdit}
  <!-- <InputText bind:val={text} onInput={onInput} onBlur={handleBlur} doAutofocus={true}/> <InputInt bind:val={done}/> <InputInt bind:val={todo}/> -->
  <div class="planTodoEntry">
    <div class="planTodoEntryText">
      <InputText bind:val={text} doAutofocus={true}/> 
    </div>
    <div class="planTodoIntegerInput">
      <InputInt bind:val={done}/>   
    </div>
    <div class="planTodoIntegerInput">
      <InputInt bind:val={todo}/>
    </div>
    <div class="planTodoButton">
      <InvertableButton label="Journal" icon="/check-solid.svg" clickHandler={saveEntry}/>
    </div>
    <div class="planTodoButton">
      <InvertableButton label="Journal" icon="/xmark-solid.svg" clickHandler={deleteEntry}/>
    </div>
  </div>
{:else}
  <div class="editableEntry" on:click={onClick}>
    {#if todo}
      <div class="planTodoEntry">
        <div class="planTodoEntryText">
          <b>{text}</b> 
        </div>
        <div class="planTodoEntryTodo">
          {done}/{todo}
        </div>
      </div>
    {:else}
      <div class="planTodoEntry">
        <div class="planTodoEntryText">
          <b>{text}</b> 
        </div>
        <div class="planTodoEntryTodo">
        </div>
      </div>
    {/if}
  </div>
{/if}

<style>
  .editableEntry {
    width: 100%;
  }

  .planTodoEntry {
    display: flex;
  }

  .planTodoEntryText {
    margin: 0 auto;
    flex-grow: 1; 
  }

  .planTodoButton {
    height: 2rem;
    width: 2rem;
  }

  .planTodoIntegerInput {
    flex-basis: 30px;
  }
  
  .planTodoEntryTodo {
    min-width: 3rem;
  }

  div {
    border: 1px solid;
  }

</style>