<script lang="ts">
  import UnsavedChangesDialog from "./UnsavedChangesDialog.svelte";
  import ModalShell from "./ModalShell.svelte";
  import { unsavedChangesGuard } from "$lib/dirtyStateGuard";

  /**
   * Example of how to use the unsaved changes guard with a modal.
   * This component shows the pattern you should follow.
   */

  export let isOpen = false;
  export let onClose: () => void = () => {};
  export let onSave: (data: any) => Promise<void> = async () => {};

  let formData = {
    name: "",
    description: "",
  };

  let showConfirmation = false;
  let isSaving = false;
  let error = "";

  // Initialize the guard
  const guard = unsavedChangesGuard({
    title: "Unsaved Changes",
    message:
      "You have unsaved changes. Do you want to discard them and leave?",
  });

  function handleInputChange() {
    guard.markDirty();
  }

  async function handleSave() {
    error = "";
    isSaving = true;
    try {
      await onSave(formData);
      guard.markClean();
      isOpen = false;
    } catch (err) {
      error = err instanceof Error ? err.message : "Failed to save";
    } finally {
      isSaving = false;
    }
  }

  function handleCloseClick() {
    if (guard.isDirty) {
      showConfirmation = true;
    } else {
      isOpen = false;
    }
  }

  function handleDiscardChanges() {
    guard.reset();
    isOpen = false;
  }

  function handleCancelConfirmation() {
    showConfirmation = false;
  }
</script>

<ModalShell {isOpen} title="Example Form with Save Guard" onClose={handleCloseClick}>
  <div class="modal-body">
    {#if error}
      <div class="error-banner">
        <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}

    <div class="form-group">
      <label for="name">Name</label>
      <input
        id="name"
        type="text"
        bind:value={formData.name}
        on:input={handleInputChange}
        placeholder="Enter name"
        disabled={isSaving}
      />
    </div>

    <div class="form-group">
      <label for="description">Description</label>
      <textarea
        id="description"
        bind:value={formData.description}
        on:input={handleInputChange}
        placeholder="Enter description"
        disabled={isSaving}
        rows="4"
      ></textarea>
    </div>
  </div>

  <svelte:fragment slot="footer">
    <button
      type="button"
      class="btn-cancel"
      on:click={handleCloseClick}
      disabled={isSaving}
    >
      {guard.isDirty ? "Cancel" : "Close"}
    </button>
    <button
      type="button"
      class="btn-submit"
      on:click={handleSave}
      disabled={!guard.isDirty || isSaving}
    >
      {isSaving ? "Saving..." : "Save Changes"}
    </button>
  </svelte:fragment>
</ModalShell>

<UnsavedChangesDialog
  bind:isOpen={showConfirmation}
  title={guard.getConfirmationOptions().title}
  message={guard.getConfirmationOptions().message}
  onDiscard={handleDiscardChanges}
  onCancel={handleCancelConfirmation}
/>

<style>
  .modal-body {
    padding: 18px 22px;
    overflow-y: auto;
    flex: 1;
  }

  .error-banner {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    margin-bottom: 16px;
    background: rgba(220, 38, 38, 0.08);
    border: 1px solid rgba(220, 38, 38, 0.2);
    border-radius: 8px;
    font-size: 13px;
    color: #dc2626;
  }

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

  label {
    font-size: 12.5px;
    font-weight: 600;
    color: var(--text-secondary);
  }

  input,
  textarea {
    padding: 8px 12px;
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    background: var(--bg-inset);
    font-size: 13px;
    color: var(--text-primary);
    font-family: inherit;
  }

  input:focus,
  textarea:focus {
    outline: none;
    border-color: var(--input-focus-border);
    box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.1);
  }

  input::placeholder,
  textarea::placeholder {
    color: var(--text-muted);
  }

  .btn-cancel {
    padding: 7px 16px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    background: var(--bg-inset);
    border: 1px solid var(--border-subtle);
    color: var(--text-secondary);
    transition: all 0.15s;
  }

  .btn-cancel:hover:not(:disabled) {
    background: var(--card-hover-bg);
    border-color: var(--border-default);
    color: var(--text-primary);
  }

  .btn-submit {
    padding: 7px 18px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    background: var(--accent-color, #0066cc);
    border: none;
    color: #fff;
    transition: filter 0.15s;
  }

  .btn-submit:hover:not(:disabled) {
    filter: brightness(1.1);
  }

  .btn-submit:disabled {
    opacity: 0.45;
    cursor: not-allowed;
  }
</style>
