<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import ClaimIcon from "$lib/ui/icons/ClaimIcon.svelte";
  import UnassignIcon from "$lib/ui/icons/UnassignIcon.svelte";
  import EditIcon from "$lib/ui/icons/EditIcon.svelte";
  import CalendarEditIcon from "$lib/ui/icons/CalendarEditIcon.svelte";

  export let isAssigned: boolean;
  export let canUnassign: boolean;
  export let busy: boolean;
  export let completed: boolean;

  export let editingText: boolean;

  export let editingDate: boolean;
  export let dateValue: string = "";

  const dispatch = createEventDispatcher<{
    claim: void;
    unassign: void;
    toggleEditText: void;
    saveText: void;
    cancelText: void;
    toggleEditDate: void;
    saveDate: { value: string | null };
    clearDate: void;
    cancelDate: void;
  }>();

  let localDate = dateValue;
  $: if (editingDate) {
    localDate = dateValue;
  }
</script>

{#if !completed}
  {#if !isAssigned}
    <button
      class="icon-btn secondary-action"
      aria-label="Reclamar"
      on:click|preventDefault={() => dispatch("claim")}
      disabled={busy}
    >
      <ClaimIcon /> Reclamar
    </button>
  {:else}
    <button
      class="icon-btn secondary-action"
      aria-label="Soltar"
      title={canUnassign ? "Soltar" : "No puedes soltar una tarea personal. Márcala como completada para eliminarla"}
      on:click|preventDefault={() => dispatch("unassign")}
      disabled={busy || !canUnassign}
    >
      <UnassignIcon /> Soltar
    </button>
  {/if}

  {#if !editingText}
    <button
      class="icon-btn secondary-action"
      aria-label="Editar texto"
      title="Editar texto"
      on:click|preventDefault={() => dispatch("toggleEditText")}
      disabled={busy}
    >
      <EditIcon /> Editar
    </button>
  {:else}
    <button class="btn primary secondary-action" on:click|preventDefault={() => dispatch("saveText")} disabled={busy}>
      Guardar
    </button>
    <button class="btn ghost secondary-action" on:click|preventDefault={() => dispatch("cancelText")} disabled={busy}>
      Cancelar
    </button>
  {/if}

  {#if !editingDate}
    <button
      class="icon-btn secondary-action"
      aria-label="Editar fecha"
      title="Editar fecha"
      on:click|preventDefault={() => dispatch("toggleEditDate")}
      disabled={busy}
    >
      <CalendarEditIcon /> Fecha
    </button>
  {:else}
    <input class="date" type="date" bind:value={localDate} />
    <button
      class="btn primary secondary-action"
      on:click|preventDefault={() => dispatch("saveDate", { value: (localDate || "").trim() || null })}
      disabled={busy}
    >
      Guardar
    </button>
    <button class="btn danger secondary-action" on:click|preventDefault={() => dispatch("clearDate")} disabled={busy}>
      Quitar
    </button>
    <button class="btn ghost secondary-action" on:click|preventDefault={() => dispatch("cancelDate")} disabled={busy}>
      Cancelar
    </button>
  {/if}
{/if}
