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

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

  export let isOpen = false;
  export let canCancel = false;
  export let canSend = true;
  export let error: string | null = null;
  export let isSubmitting = false;

  let selectedDecision: ReviewDecision | null = null;
  let note = "";
  let includeTimeEntry = false;
  let timeStarted = "";
  let timeEnded = "";
  let noteError = "";
  let showSendQuoteConfirm = false;

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

  const decisions: {
    key: ReviewDecision;
    label: string;
    desc: string;
    class: string;
  }[] = [
    {
      key: "approve",
      label: "Approve",
      desc: "Approve and move to Pending Sent",
      class: "wf-decision-approve",
    },
    {
      key: "reject",
      label: "Reject",
      desc: "Send back for revision",
      class: "wf-decision-reject",
    },
    {
      key: "send",
      label: "Send Quote",
      desc: "Approve and send quote immediately",
      class: "wf-decision-send",
    },
    {
      key: "cancel",
      label: "Cancel",
      desc: "Cancel the opportunity",
      class: "wf-decision-cancel",
    },
  ];

  function selectDecision(d: ReviewDecision) {
    if (d === "cancel" && !canCancel) return;
    if (d === "send" && !canSend) return;
    selectedDecision = d;
    noteError = "";
    showSendQuoteConfirm = false;
  }

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

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

    // If "send" was chosen, confirm then transition to SendQuote modal
    if (selectedDecision === "send") {
      showSendQuoteConfirm = true;
      return;
    }

    const payload: WorkflowActionPayload = {
      decision: selectedDecision,
    };
    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 handleSendQuoteConfirm() {
    // First submit the review decision with "send", then open SendQuote modal
    const payload: WorkflowActionPayload = {
      decision: "send" as ReviewDecision,
    };
    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;
    selectedDecision = null;
    note = "";
    includeTimeEntry = false;
    timeStarted = "";
    timeEnded = "";
    noteError = "";
    showSendQuoteConfirm = false;
    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="Finish Review"
    tabindex="-1"
  >
    <div class="wf-modal wf-modal-wide" on:click|stopPropagation>
      <div class="wf-modal-header wf-header-accent">
        <h3 class="wf-modal-title">Finish Review</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 showSendQuoteConfirm}
          <!-- Send Quote confirmation step -->
          <div class="wf-confirmation-box">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              width="20"
              height="20"
            >
              <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" />
            </svg>
            <p>
              This will approve the review and send the quote. The send quote
              form will allow you to set additional options.
            </p>
            <div class="wf-confirmation-actions">
              <button
                class="wf-btn wf-btn-secondary"
                on:click={() => (showSendQuoteConfirm = false)}
                disabled={isSubmitting}
              >
                Go Back
              </button>
              <button
                class="wf-btn wf-btn-primary"
                on:click={handleSendQuoteConfirm}
                disabled={isSubmitting}
              >
                {#if isSubmitting}
                  <span class="wf-spinner"></span>
                {:else}
                  Continue to Send Quote
                {/if}
              </button>
            </div>
          </div>
        {:else}
          <!-- Decision selector -->
          <div class="wf-decision-group">
            <span class="wf-field-label">Decision</span>
            <div class="wf-decision-buttons">
              {#each decisions as d (d.key)}
                {@const isDisabled =
                  (d.key === "cancel" && !canCancel) ||
                  (d.key === "send" && !canSend)}
                <button
                  class="wf-decision-btn {d.class}"
                  class:wf-selected={selectedDecision === d.key}
                  class:wf-disabled-perm={isDisabled}
                  on:click={() => selectDecision(d.key)}
                  disabled={isSubmitting || isDisabled}
                  title={isDisabled
                    ? d.key === "cancel"
                      ? "You don't have permission to cancel opportunities"
                      : "You don't have permission to send quotes"
                    : d.desc}
                >
                  {d.label}
                </button>
              {/each}
            </div>
            {#if selectedDecision}
              <span class="wf-decision-desc">
                {decisions.find((d) => d.key === selectedDecision)?.desc ?? ""}
              </span>
            {/if}
          </div>

          <!-- Note field (always required for review) -->
          <div class="wf-field-group">
            <label class="wf-field-label" for="rd-note">
              Note <span class="wf-required">*</span>
            </label>
            <textarea
              id="rd-note"
              class="wf-textarea"
              class:wf-field-error={!!noteError}
              bind:value={note}
              placeholder="Explain the review decision..."
              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="rd-time-start">Start</label
                  >
                  <input
                    id="rd-time-start"
                    type="datetime-local"
                    class="wf-input"
                    bind:value={timeStarted}
                  />
                </div>
                <div class="wf-time-field">
                  <label class="wf-field-label" for="rd-time-end">End</label>
                  <input
                    id="rd-time-end"
                    type="datetime-local"
                    class="wf-input"
                    bind:value={timeEnded}
                  />
                </div>
              </div>
            {/if}
          </div>
        {/if}
      </div>

      {#if !showSendQuoteConfirm}
        <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 || !selectedDecision}
          >
            {#if isSubmitting}
              <span class="wf-spinner"></span>
            {:else}
              Submit Decision
            {/if}
          </button>
        </div>
      {/if}
    </div>
  </div>
{/if}
