<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 canFinalize = false;
  export let error: string | null = null;
  export let isSubmitting = false;
  export let actionName: WorkflowAction = "sendQuote";

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

  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();

  let quoteConfirmed = false;
  // Sub-option: only one can be selected at a time
  type SubOption = "won" | "lost" | "revision" | null;
  let selectedSubOption: SubOption = null;
  let finalizeImmediately = canFinalize;

  // Reset finalize toggle when canFinalize changes
  $: finalizeImmediately = canFinalize;

  function toggleConfirmed() {
    quoteConfirmed = !quoteConfirmed;
    if (!quoteConfirmed) selectedSubOption = null;
  }

  function selectSub(opt: SubOption) {
    if (!quoteConfirmed) return;
    selectedSubOption = selectedSubOption === opt ? null : opt;
  }

  function handleSubmit() {
    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();
    payload.quoteConfirmed = quoteConfirmed;
    payload.won = selectedSubOption === "won";
    payload.lost = selectedSubOption === "lost";
    payload.needsRevision = selectedSubOption === "revision";
    if (
      (selectedSubOption === "won" || selectedSubOption === "lost") &&
      canFinalize
    ) {
      payload.finalize = finalizeImmediately;
    }
    dispatch("submit", payload);
  }

  function handleClose() {
    if (isSubmitting) return;
    note = "";
    includeTimeEntry = false;
    timeStarted = "";
    timeEnded = "";
    quoteConfirmed = false;
    selectedSubOption = null;
    finalizeImmediately = canFinalize;
    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();
    }
  }

  $: title = actionName === "resendQuote" ? "Re-Send Quote" : "Send Quote";
</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 wf-modal-wide" on:click|stopPropagation>
      <div class="wf-modal-header">
        <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}

        <!-- Note field -->
        <div class="wf-field-group">
          <label class="wf-field-label" for="sq-note">
            Note <span class="wf-optional">(optional)</span>
          </label>
          <textarea
            id="sq-note"
            class="wf-textarea"
            bind:value={note}
            placeholder="Add a note about this quote..."
            rows="3"
          ></textarea>
        </div>

        <!-- Quote outcome options -->
        <div class="sq-outcome-section">
          <button
            class="sq-confirmed-toggle"
            class:sq-active={quoteConfirmed}
            on:click={toggleConfirmed}
            disabled={isSubmitting}
            type="button"
          >
            <span class="sq-toggle-check">
              {#if quoteConfirmed}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2.5"
                  width="14"
                  height="14"><polyline points="20 6 9 17 4 12" /></svg
                >
              {:else}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="1.5"
                  width="14"
                  height="14"
                  opacity="0.3"><circle cx="12" cy="12" r="9" /></svg
                >
              {/if}
            </span>
            <span class="sq-toggle-label">Quote Confirmed</span>
            <span class="sq-toggle-hint">Customer confirmed receipt</span>
          </button>

          {#if quoteConfirmed}
            <div class="sq-sub-options" transition:slide={{ duration: 180 }}>
              <button
                class="sq-sub-option"
                class:sq-sub-active={selectedSubOption === "won"}
                on:click={() => selectSub("won")}
                disabled={isSubmitting}
                type="button"
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="15"
                  height="15"
                  ><path d="M22 11.08V12a10 10 0 11-5.93-9.14" /><polyline
                    points="22 4 12 14.01 9 11.01"
                  /></svg
                >
                <span class="sq-sub-label">Won</span>
                <span class="sq-sub-desc">
                  {canFinalize ? "Finalize as won" : "Send to Pending Won"}
                </span>
              </button>

              <button
                class="sq-sub-option"
                class:sq-sub-active={selectedSubOption === "lost"}
                on:click={() => selectSub("lost")}
                disabled={isSubmitting}
                type="button"
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="15"
                  height="15"
                  ><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 class="sq-sub-label">Lost</span>
                <span class="sq-sub-desc">Send to Pending Lost</span>
              </button>

              <button
                class="sq-sub-option"
                class:sq-sub-active={selectedSubOption === "revision"}
                on:click={() => selectSub("revision")}
                disabled={isSubmitting}
                type="button"
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="15"
                  height="15"
                  ><path
                    d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"
                  /><path
                    d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"
                  /></svg
                >
                <span class="sq-sub-label">Needs Revision</span>
                <span class="sq-sub-desc"
                  >Requires changes before finalizing</span
                >
              </button>
            </div>

            {#if (selectedSubOption === "won" || selectedSubOption === "lost") && canFinalize}
              <div class="sq-finalize-row" transition:slide={{ duration: 150 }}>
                <label class="sq-finalize-check">
                  <input type="checkbox" bind:checked={finalizeImmediately} />
                  <span>Finalize immediately</span>
                  <span class="sq-finalize-hint"
                    >{finalizeImmediately
                      ? "Will finalize directly"
                      : "Will go to pending review"}</span
                  >
                </label>
              </div>
            {/if}
          {/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="sq-time-start">Start</label>
                <input
                  id="sq-time-start"
                  type="datetime-local"
                  class="wf-input"
                  bind:value={timeStarted}
                />
              </div>
              <div class="wf-time-field">
                <label class="wf-field-label" for="sq-time-end">End</label>
                <input
                  id="sq-time-end"
                  type="datetime-local"
                  class="wf-input"
                  bind:value={timeEnded}
                />
              </div>
            </div>
          {/if}
        </div>
      </div>

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