<script context="module" lang="ts">
  type Props = {
    createMachine: () => Machine<any, any>;
    onClick?: (event: any) => void | false;
    mapStateFn?: (state: string) => string;
    renderLabel?: (props: { status: any; error: string | null }) => any;
    statusChangeFn?: (status: any, prevStatus: any) => void;
    idleLabel?: string;
    loadingLabel?: string;
    successLabel?: string;
    errorLabel?: string;
    className?: string;
    unstyled?: boolean;
    buttonRef?: any;
    ref?: any;
  };
</script>

<script lang="ts">
  import { onMount } from "svelte";

  import clsx from "clsx";
  import type { Machine, Service } from "robot3";
  import { interpret } from "robot3";
  import { callFns } from "../lib/call-fns";
  import { mapState } from "./internal/map-state";
  import { toast } from "./sonner/state";

  export let createMachine: Props["createMachine"];
  export let mapStateFn: Props["mapStateFn"] = undefined;
  export let statusChangeFn: Props["statusChangeFn"] = undefined;
  export let idleLabel: Props["idleLabel"] = undefined;
  export let loadingLabel: Props["loadingLabel"] = undefined;
  export let successLabel: Props["successLabel"] = undefined;
  export let errorLabel: Props["errorLabel"] = undefined;
  export let renderLabel: Props["renderLabel"] = undefined;
  export let onClick: Props["onClick"] = undefined;
  export let buttonRef: Props["buttonRef"] = undefined;
  export let unstyled: Props["unstyled"] = undefined;
  export let className: Props["className"] = undefined;

  function handleClick(event: any) {
    callFns(event, onClick, () => {
      if (current === "active") {
        service?.send("discard");
      } else {
        service?.send("start");
      }
    });
  }
  $: getLabel = () => {
    const c = service?.context;
    const mapper = mapStateFn || mapState;
    const status = mapper(current);
    const error = status === "error" && c ? c.error : null;

    // props[`${status}Label`] does not translate to svelte, hence the switch
    switch (true) {
      case status === "idle" && typeof idleLabel === "string":
        return idleLabel;
      case status === "loading" && typeof loadingLabel === "string":
        return loadingLabel;
      case status === "success" && typeof successLabel === "string":
        return successLabel;
      case status === "error" && typeof errorLabel === "string":
        return errorLabel;
      case typeof renderLabel === "function":
        return renderLabel({
          status,
          error,
        });
      case status === "error" && error:
        return `Error: ${error}`;
      default:
        return status === "success" ? "discard" : "enable";
    }
  };

  let prev = null;
  let current = "init";
  let lastToast = null;
  let service = null;

  onMount(() => {
    const m = createMachine();
    const s = interpret(m, (c) => {
      current = c.machine.current;
    });
    current = s.machine.current;
    service = s;
  });

  function onUpdateFn_0(..._args: any[]) {
    const mapper = mapStateFn || mapState;
    const newStatus = mapper(current);
    const prevStatus = prev ? mapper(prev) : null;
    if (newStatus !== prevStatus && statusChangeFn) {
      statusChangeFn(newStatus, prevStatus);
    }
    prev = current;
  }

  $: onUpdateFn_0(...[current]);

  function onUpdateFn_1(..._args: any[]) {
    const mapper = mapStateFn || mapState;
    const status = mapper(current);
    const context = service?.context as {
      error?: string;
      errorDetail?: string;
    };
    const message = status === "error" ? context?.error : null;
    const detail = status === "error" ? context?.errorDetail : null;
    if (!message) {
      lastToast = null;
      return;
    }
    const toastKey = detail ? `${message}::${detail}` : message;
    if (toastKey === lastToast) return;
    toast.error(message, {
      description: detail || undefined,
    });
    lastToast = toastKey;
  }

  $: onUpdateFn_1(...[current]);
</script>

<button
  data-status={(mapStateFn || mapState)(current)}
  on:click={(event) => {
    handleClick(event);
  }}
  bind:this={buttonRef}
  class={clsx(
    {
      "magicbell--button": !unstyled,
    },
    className
  )}>{getLabel()}</button
>