<script lang="ts">
import type { Snippet } from 'svelte';
import { connect, machine } from '@zag-js/dialog';
import { normalizeProps, portal, useMachine } from '@zag-js/svelte';

import { IconButton } from './button';

interface Props {
  /** Whether the modal is open. */
  isOpen?: boolean;

  /** Accessible role of the modal. */
  role?: 'dialog' | 'alertdialog';

  /** The modal title */
  title: string;

  /** An optional subtitle */
  subtitle?: Snippet;

  /** The modal size */
  size?: 'small' | 'medium' | 'large' | 'extra-large';

  contentPadding?: string;

  /** Whether the content should clip overflow or not */
  clipOverflow?: boolean;

  onClose?: () => void;
  content: Snippet;
  footer?: Snippet;

  /**
   * Returns the element that should receive focus on open. Return `null` to
   * skip the default first-tabbable behavior (focus-trap will fall back to the
   * content container). Omit to use the default.
   */
  initialFocusEl?: () => HTMLElement | null;
}

const {
  isOpen = false,
  size = 'small',
  role,
  title,
  subtitle,
  contentPadding = 'p-4',
  clipOverflow = true,
  onClose,
  content,
  footer,
  initialFocusEl,
}: Props = $props();

const id = $props.id();
const service = useMachine(machine, {
  id,
  get open() {
    return isOpen;
  },
  get role() {
    return role;
  },
  get initialFocusEl() {
    return initialFocusEl;
  },
  onOpenChange(event) {
    if (event.open) {
      return;
    }

    onClose?.();
  },
});

const api = $derived(connect(service, normalizeProps));

const closeButtonProps = $derived(() => {
  const props = api.getCloseTriggerProps();
  const filtered: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(props)) {
    if (value !== null) {
      filtered[key] = value;
    }
  }
  return filtered;
});
</script>

{#if api.open}
  <div
    use:portal
    {...api.getBackdropProps()}
    class="fixed inset-0 z-1400 bg-black/40"
  ></div>
  <div
    use:portal
    {...api.getPositionerProps()}
    class="fixed inset-0 z-1400 flex h-screen w-screen items-center justify-center"
  >
    <div
      {...api.getContentProps()}
      class={[
        {
          'max-w-[25rem]': size === 'small',
          'max-w-[37.5rem]': size === 'medium',
          'max-w-[50rem]': size === 'large',
          'max-w-[60rem]': size === 'extra-large',
        },
        'border-medium relative m-4 flex max-h-[calc(100vh-2rem)] min-h-0 w-full flex-col border bg-white shadow-sm',
      ]}
    >
      <div class="flex shrink-0 justify-between p-4">
        <div class="flex flex-col gap-0.5">
          <h2
            {...api.getTitleProps()}
            class="text-default text-lg font-semibold"
          >
            {title}
          </h2>

          {#if subtitle}
            <p class="text-subtle-1 text-sm">
              {@render subtitle()}
            </p>
          {/if}
        </div>

        <IconButton
          {...closeButtonProps()}
          icon="close"
          label="Close modal"
          variant="ghost"
          on:click={() => onClose?.()}
          cx="h-6 w-6 shrink-0"
        />
      </div>

      {#if content}
        <div
          class={[
            'text-subtle-1 grow border-t text-sm',
            contentPadding ?? '',
            clipOverflow && 'overflow-auto',
          ]}
        >
          {@render content()}
        </div>
      {/if}

      {#if footer}
        <div class="flex shrink-0 justify-end gap-2 border-t px-4 py-3">
          {@render footer()}
        </div>
      {/if}
    </div>
  </div>
{/if}
