<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import { slide } from "svelte/transition";
  import type {
    WorkflowAction,
    WorkflowActionPayload,
  } from "$lib/optima-api/modules/sales";

  const dispatch = createEventDispatcher<{
    submit: WorkflowActionPayload;
    close: void;
  }>();

  export let isOpen = false;
  export let title = "Workflow Action";
  export let actionName: WorkflowAction;
  export let requiresNote = false;
  export let needsConfirmation = false;
  export let confirmationMessage = "";
  export let isDestructive = false;
  export let error: string | null = null;
  export let isSubmitting = false;

  let note = "";
  let includeTimeEntry = false;
  let timeStarted = "";
  let timeEnded = "";
  let showConfirmation = false;
  let noteError = "";

  function toLocalDatetime(d: Date): string {
    const y = d.getFullYear();
    const mo = String(d.getMonth() + 1).padStart(2, "0");
    const da = String(d.getDate()).padStart(2, "0");
    const h = String(d.getHours()).padStart(2, "0");
    const mi = String(d.getMinutes()).padStart(2, "0");
    return `${y}-${mo}-${da}T${h}:${mi}`;
  }

  function initTimes() {
    const now = new Date();
    const mins = now.getMinutes();
    const roundedUp = Math.ceil(mins / 15) * 15;
    const ended = new Date(now);
    ended.setMinutes(roundedUp, 0, 0);
    const started = new Date(ended.getTime() - 15 * 60 * 1000);
    timeEnded = toLocalDatetime(ended);
    timeStarted = toLocalDatetime(started);
  }

  initTimes();

  function validate(): boolean {
    noteError = "";
    if (requiresNote && !note.trim()) {
      noteError = "A note is required for this action.";
      return false;
    }
    return true;
  }

  function handleSubmit() {
    if (!validate()) return;
    if (needsConfirmation && !showConfirmation) {
      showConfirmation = true;
      return;
    }

    const payload: WorkflowActionPayload = {};
    if (note.trim()) payload.note = note.trim();
    if (includeTimeEntry && timeStarted)
      payload.timeStarted = new Date(timeStarted).toISOString();
    if (includeTimeEntry && timeEnded)
      payload.timeEnded = new Date(timeEnded).toISOString();
    dispatch("submit", payload);
  }

  function handleConfirm() {
    const payload: WorkflowActionPayload = {};
    if (note.trim()) payload.note = note.trim();
    if (includeTimeEntry && timeStarted)
      payload.timeStarted = new Date(timeStarted).toISOString();
    if (includeTimeEntry && timeEnded)
      payload.timeEnded = new Date(timeEnded).toISOString();
    dispatch("submit", payload);
  }

  function handleClose() {
    if (isSubmitting) return;
    note = "";
    includeTimeEntry = false;
    timeStarted = "";
    timeEnded = "";
    showConfirmation = false;
    noteError = "";
    dispatch("close");
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key === "Escape") handleClose();
  }

  function handleBackdropClick(e: MouseEvent) {
    if ((e.target as HTMLElement).classList.contains("wf-modal-backdrop")) {
      handleClose();
    }
  }
</script>

{#if isOpen}
  <div
    class="wf-modal-backdrop"
    on:click={handleBackdropClick}
    on:keydown={handleKeydown}
    role="dialog"
    aria-modal="true"
    aria-label={title}
    tabindex="-1"
  >
    <div class="wf-modal" on:click|stopPropagation>
      <div class="wf-modal-header" class:wf-destructive={isDestructive}>
        <h3 class="wf-modal-title">{title}</h3>
        <button
          class="wf-modal-close"
          on:click={handleClose}
          disabled={isSubmitting}
          aria-label="Close"
        >
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            width="16"
            height="16"
          >
            <line x1="18" y1="6" x2="6" y2="18" /><line
              x1="6"
              y1="6"
              x2="18"
              y2="18"
            />
          </svg>
        </button>
      </div>

      <div class="wf-modal-body">
        {#if error}
          <div class="wf-inline-error">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              width="14"
              height="14"
            >
              <circle cx="12" cy="12" r="10" /><line
                x1="15"
                y1="9"
                x2="9"
                y2="15"
              /><line x1="9" y1="9" x2="15" y2="15" />
            </svg>
            <span>{error}</span>
          </div>
        {/if}

        {#if showConfirmation}
          <div class="wf-confirmation-box">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              width="20"
              height="20"
            >
              <path
                d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"
              />
              <line x1="12" y1="9" x2="12" y2="13" /><line
                x1="12"
                y1="17"
                x2="12.01"
                y2="17"
              />
            </svg>
            <p>{confirmationMessage}</p>
            <div class="wf-confirmation-actions">
              <button
                class="wf-btn wf-btn-secondary"
                on:click={() => (showConfirmation = false)}
                disabled={isSubmitting}
              >
                Go Back
              </button>
              <button
                class="wf-btn {isDestructive
                  ? 'wf-btn-destructive'
                  : 'wf-btn-primary'}"
                on:click={handleConfirm}
                disabled={isSubmitting}
              >
                {#if isSubmitting}
                  <span class="wf-spinner"></span>
                {:else}
                  Confirm
                {/if}
              </button>
            </div>
          </div>
        {:else}
          <!-- Note field -->
          <div class="wf-field-group">
            <label class="wf-field-label" for="wf-note">
              Note {#if requiresNote}<span class="wf-required">*</span>{/if}
            </label>
            <textarea
              id="wf-note"
              class="wf-textarea"
              class:wf-field-error={!!noteError}
              bind:value={note}
              placeholder={requiresNote
                ? "Required — describe this action"
                : "Optional note"}
              rows="4"
            ></textarea>
            {#if noteError}
              <span class="wf-field-error-text">{noteError}</span>
            {/if}
          </div>

          <!-- Time entry section -->
          <div class="wf-time-section">
            <label class="wf-time-toggle">
              <input type="checkbox" bind:checked={includeTimeEntry} />
              <svg
                width="14"
                height="14"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                ><circle cx="12" cy="12" r="10" /><polyline
                  points="12 6 12 12 16 14"
                /></svg
              >
              <span>Log time</span>
            </label>
            {#if includeTimeEntry}
              <div class="wf-time-fields" transition:slide={{ duration: 200 }}>
                <div class="wf-time-field">
                  <label class="wf-field-label" for="wf-time-start">Start</label
                  >
                  <input
                    id="wf-time-start"
                    type="datetime-local"
                    class="wf-input"
                    bind:value={timeStarted}
                  />
                </div>
                <div class="wf-time-field">
                  <label class="wf-field-label" for="wf-time-end">End</label>
                  <input
                    id="wf-time-end"
                    type="datetime-local"
                    class="wf-input"
                    bind:value={timeEnded}
                  />
                </div>
              </div>
            {/if}
          </div>
        {/if}
      </div>

      {#if !showConfirmation}
        <div class="wf-modal-footer">
          <button
            class="wf-btn wf-btn-secondary"
            on:click={handleClose}
            disabled={isSubmitting}
          >
            Cancel
          </button>
          <button
            class="wf-btn {isDestructive
              ? 'wf-btn-destructive'
              : 'wf-btn-primary'}"
            on:click={handleSubmit}
            disabled={isSubmitting}
          >
            {#if isSubmitting}
              <span class="wf-spinner"></span>
            {:else}
              {title}
            {/if}
          </button>
        </div>
      {/if}
    </div>
  </div>
{/if}
