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

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

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

  type ActivityTypeValue = "Follow-Up" | "Appointment" | "Admin";

  let activityTypeValue: ActivityTypeValue = "Follow-Up";
  let startDate = "";
  let startHour = "";
  let endDate = "";
  let endHour = "";
  let notes = "";
  let timeError = "";

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

  function toLocalTime(d: Date): string {
    const h = String(d.getHours()).padStart(2, "0");
    const mi = String(d.getMinutes()).padStart(2, "0");
    return `${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);
    if (ended <= now) ended.setHours(ended.getHours() + 1);
    const started = new Date(ended.getTime() - 60 * 60 * 1000);
    startDate = toLocalDate(started);
    startHour = toLocalTime(started);
    endDate = toLocalDate(ended);
    endHour = toLocalTime(ended);
  }
  initTimes();

  function validate(): boolean {
    timeError = "";
    if (startDate && startHour && endDate && endHour) {
      const s = new Date(`${startDate}T${startHour}`);
      const e = new Date(`${endDate}T${endHour}`);
      if (e <= s) {
        timeError = "End time must be after start time.";
        return false;
      }
    }
    return true;
  }

  function handleSubmit() {
    if (!validate()) return;
    const startIso = startDate && startHour ? new Date(`${startDate}T${startHour}`).toISOString() : undefined;
    const endIso   = endDate   && endHour   ? new Date(`${endDate}T${endHour}`).toISOString()     : undefined;
    const payload: WorkflowActionPayload = {
      activityTypeValue,
      dueDate: endDate || undefined,
      startTime: startIso,
      endTime: endIso,
      note: notes.trim() || undefined,
    };
    dispatch("submit", payload);
  }

  function handleClose() {
    if (isSubmitting) return;
    timeError = "";
    notes = "";
    initTimes();
    dispatch("close");
  }

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

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

{#if isOpen}
  <div
    class="wf-modal-backdrop"
    on:click={handleBackdropClick}
    on:keydown={handleKeydown}
    role="dialog"
    aria-modal="true"
    aria-label="Create Schedule Entry"
    tabindex="-1"
  >
    <div class="wf-modal" on:click|stopPropagation>
      <div class="wf-modal-header">
        <h3 class="wf-modal-title">Create Schedule Entry</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="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
            </svg>
            {error}
          </div>
        {/if}

        <!-- Activity Type pills -->
        <div class="se-form-group se-full-width">
          <label class="se-label">Activity Type <span class="se-req">*</span></label>
          <div class="se-type-pills">
            {#each (["Follow-Up", "Appointment", "Admin"] as const) as t}
              <button
                type="button"
                class="se-pill"
                class:se-pill-active={activityTypeValue === t}
                on:click={() => (activityTypeValue = t)}
                disabled={isSubmitting}
              >
                {#if t === "Follow-Up"}
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13">
                    <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.908.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/>
                  </svg>
                {:else if t === "Appointment"}
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13">
                    <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                    <line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
                  </svg>
                {:else}
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13">
                    <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
                  </svg>
                {/if}
                {t}
              </button>
            {/each}
          </div>
        </div>

        <!-- Date/time grid -->
        <div class="se-grid">
          <div class="se-form-group">
            <label class="se-label" for="se-start-date">Start Date</label>
            <input
              id="se-start-date"
              type="date"
              class="se-input"
              class:se-input-error={!!timeError}
              bind:value={startDate}
              disabled={isSubmitting}
              on:change={() => (timeError = "")}
            />
          </div>
          <div class="se-form-group">
            <label class="se-label" for="se-start-time">Start Time</label>
            <input
              id="se-start-time"
              type="time"
              class="se-input"
              class:se-input-error={!!timeError}
              bind:value={startHour}
              disabled={isSubmitting}
              on:change={() => (timeError = "")}
            />
          </div>
          <div class="se-form-group">
            <label class="se-label" for="se-end-date">End Date</label>
            <input
              id="se-end-date"
              type="date"
              class="se-input"
              class:se-input-error={!!timeError}
              bind:value={endDate}
              disabled={isSubmitting}
              on:change={() => (timeError = "")}
            />
          </div>
          <div class="se-form-group">
            <label class="se-label" for="se-end-time">End Time</label>
            <input
              id="se-end-time"
              type="time"
              class="se-input"
              class:se-input-error={!!timeError}
              bind:value={endHour}
              disabled={isSubmitting}
              on:change={() => (timeError = "")}
            />
          </div>
        </div>
        {#if timeError}
          <span class="se-field-error">{timeError}</span>
        {/if}

        <!-- Notes -->
        <div class="se-form-group se-full-width">
          <label class="se-label" for="se-notes">Notes <span class="se-optional">(optional)</span></label>
          <textarea
            id="se-notes"
            class="se-textarea"
            rows={3}
            placeholder="Add any notes for this schedule entry…"
            bind:value={notes}
            disabled={isSubmitting}
          ></textarea>
        </div>
      </div>

      <div class="wf-modal-footer">
        <button class="wf-action-btn wf-btn-ghost" on:click={handleClose} disabled={isSubmitting}>
          Cancel
        </button>
        <button
          class="wf-action-btn wf-btn-primary"
          on:click={handleSubmit}
          disabled={isSubmitting}
        >
          {#if isSubmitting}
            <span class="wf-spinner"></span> Creating…
          {:else}
            Create Entry
          {/if}
        </button>
      </div>
    </div>
  </div>
{/if}

<style>
  /* ── Layout ── */
  .se-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 14px;
  }

  .se-form-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
    margin-bottom: 14px;
  }

  .se-full-width {
    grid-column: 1 / -1;
  }

  /* ── Label ── */
  .se-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-muted, #888);
    text-transform: uppercase;
    letter-spacing: 0.05em;
  }

  .se-req {
    color: #ef4444;
    font-weight: 700;
  }

  .se-optional {
    font-weight: 400;
    text-transform: none;
    letter-spacing: 0;
    font-size: 11px;
  }

  /* ── Inputs ── */
  .se-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid var(--border-subtle, #ddd);
    border-radius: 8px;
    background: var(--bg-inset, #fafafa);
    font-size: 13px;
    color: var(--text-primary, #1a1a1a);
    box-sizing: border-box;
    font-family: inherit;
    transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
  }

  .se-input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.12);
    background: var(--bg-surface, #fff);
  }

  .se-input:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .se-input-error {
    border-color: #ef4444 !important;
  }

  .se-field-error {
    font-size: 11.5px;
    color: #ef4444;
    margin-top: -8px;
    margin-bottom: 8px;
    display: block;
  }

  /* ── Type pills ── */
  .se-type-pills {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .se-pill {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 6px 14px;
    border-radius: 20px;
    border: 1px solid var(--border-subtle, #ddd);
    background: transparent;
    color: var(--text-muted, #888);
    font-size: 13px;
    font-family: inherit;
    cursor: pointer;
    transition: border-color 0.15s, color 0.15s, background 0.15s;
  }

  .se-pill:hover:not(:disabled) {
    border-color: #3b82f6;
    color: #3b82f6;
  }

  .se-pill.se-pill-active {
    border-color: #3b82f6;
    background: rgba(59, 130, 246, 0.08);
    color: #3b82f6;
    font-weight: 600;
  }

  .se-pill:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  /* ── Textarea ── */
  .se-textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid var(--border-subtle, #ddd);
    border-radius: 8px;
    background: var(--bg-inset, #fafafa);
    font-size: 13px;
    color: var(--text-primary, #1a1a1a);
    box-sizing: border-box;
    resize: vertical;
    font-family: inherit;
    line-height: 1.5;
    transition: border-color 0.15s, box-shadow 0.15s;
  }

  .se-textarea:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.12);
    background: var(--bg-surface, #fff);
  }

  .se-textarea::placeholder {
    color: var(--text-muted, #aaa);
  }

  .se-textarea:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  /* ── Footer ── */
  .wf-modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
    padding: 0.75rem 1rem;
    border-top: 1px solid var(--border-color, #333);
  }
</style>
