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

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

  export let isOpen = false;
  export let statusKey: WorkflowStatusKey | null = null;
  export let hasWon = false;
  export let hasLost = false;
  export let canFinalize = false;
  export let initialOutcome: "won" | "lost" | null = null;
  export let error: string | null = null;
  export let isSubmitting = false;

  // If user has finalize permission, show checkbox (checked by default)
  // If not, the action will send to Pending Won/Lost instead
  let finalizeImmediately = canFinalize;

  let note = "";
  let includeTimeEntry = false;
  let timeStarted = "";
  let timeEnded = "";
  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();
  let selectedOutcome: "won" | "lost" | null = initialOutcome;

  // Auto-select based on initialOutcome, current pending status, or single-outcome availability
  $: if (initialOutcome && selectedOutcome === null) {
    selectedOutcome = initialOutcome;
  } else if (statusKey === "PendingWon" && hasWon && selectedOutcome === null) {
    selectedOutcome = "won";
  } else if (
    statusKey === "PendingLost" &&
    hasLost &&
    selectedOutcome === null
  ) {
    selectedOutcome = "lost";
  } else if (hasWon && !hasLost && selectedOutcome === null) {
    selectedOutcome = "won";
  } else if (hasLost && !hasWon && selectedOutcome === null) {
    selectedOutcome = "lost";
  }

  function validate(): boolean {
    noteError = "";
    if (!note.trim()) {
      noteError = "A note is required to finalize.";
      return false;
    }
    if (!selectedOutcome) {
      return false;
    }
    return true;
  }

  function handleSubmit() {
    if (!validate()) return;

    const payload: WorkflowActionPayload = {
      outcome: selectedOutcome!,
      finalize: canFinalize && finalizeImmediately,
    };
    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 = "";
    noteError = "";
    selectedOutcome = 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();
    }
  }

  $: pendingOnly = !canFinalize || !finalizeImmediately;
  $: title = pendingOnly
    ? selectedOutcome === "won"
      ? "Mark as Pending Won"
      : selectedOutcome === "lost"
        ? "Mark as Pending Lost"
        : "Mark Outcome"
    : selectedOutcome === "won"
      ? "Finalize as Won"
      : selectedOutcome === "lost"
        ? "Finalize as Lost"
        : "Finalize Opportunity";
</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-header-won={selectedOutcome === "won"}
        class:wf-header-lost={selectedOutcome === "lost"}
      >
        <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}

        <!-- Outcome selector (if both are available) -->
        {#if hasWon && hasLost}
          <div
            class="wf-finalize-selector"
            class:has-selection={selectedOutcome !== null}
            class:lost-selected={selectedOutcome === "lost"}
          >
            <button
              class="wf-finalize-option wf-finalize-won"
              class:wf-selected={selectedOutcome === "won"}
              on:click={() => (selectedOutcome = "won")}
              disabled={isSubmitting}
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                width="20"
                height="20"
              >
                <path d="M22 11.08V12a10 10 0 11-5.93-9.14" /><polyline
                  points="22 4 12 14.01 9 11.01"
                />
              </svg>
              <span>Won</span>
            </button>
            <button
              class="wf-finalize-option wf-finalize-lost"
              class:wf-selected={selectedOutcome === "lost"}
              on:click={() => (selectedOutcome = "lost")}
              disabled={isSubmitting}
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                width="20"
                height="20"
              >
                <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>Lost</span>
            </button>
          </div>
        {/if}

        <!-- Finalize checkbox (only if user has finalize permission) -->
        {#if canFinalize}
          <label class="wf-finalize-check">
            <input type="checkbox" bind:checked={finalizeImmediately} />
            <span>Finalize immediately</span>
            <span
              class="wf-info-icon"
              title="Skip the pending approval step and finalize directly to Won or Lost."
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                width="13"
                height="13"
              >
                <circle cx="12" cy="12" r="10" /><line
                  x1="12"
                  y1="16"
                  x2="12"
                  y2="12"
                /><line x1="12" y1="8" x2="12.01" y2="8" />
              </svg>
            </span>
          </label>
        {/if}

        <!-- Pending disclaimer -->
        {#if pendingOnly}
          <div class="wf-pending-notice">
            <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="12"
                y1="16"
                x2="12"
                y2="12"
              /><line x1="12" y1="8" x2="12.01" y2="8" />
            </svg>
            <span
              >This will set the opportunity to <strong
                >Pending {selectedOutcome === "won"
                  ? "Won"
                  : selectedOutcome === "lost"
                    ? "Lost"
                    : "Won/Lost"}</strong
              > for manager reviewal before finalizing.</span
            >
          </div>
        {/if}

        <!-- Note field (required) -->
        <div class="wf-field-group">
          <label class="wf-field-label" for="fin-note">
            Note <span class="wf-required">*</span>
          </label>
          <textarea
            id="fin-note"
            class="wf-textarea"
            class:wf-field-error={!!noteError}
            bind:value={note}
            placeholder="Explain the finalization..."
            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="fin-time-start">Start</label>
                <input
                  id="fin-time-start"
                  type="datetime-local"
                  class="wf-input"
                  bind:value={timeStarted}
                />
              </div>
              <div class="wf-time-field">
                <label class="wf-field-label" for="fin-time-end">End</label>
                <input
                  id="fin-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 {selectedOutcome === 'won'
            ? 'wf-btn-success'
            : 'wf-btn-danger'}"
          on:click={handleSubmit}
          disabled={isSubmitting || !selectedOutcome}
        >
          {#if isSubmitting}
            <span class="wf-spinner"></span>
          {:else}
            {title}
          {/if}
        </button>
      </div>
    </div>
  </div>
{/if}
