<script lang="ts">
  import { goto } from '$app/navigation';
	import Icon from "@iconify/svelte";
	import Loading from './Loading.svelte';

  export let theme: "light" | "dark" | "blue" | "pink" | "red"  = "light";
  export let size: "md" | "lg" = "md";
  export let href: string | undefined = undefined;
  export let icon: string | undefined = undefined;
  export let target: "_blank" | "_self" | undefined = undefined;
  export let iconPosition: "left" | "right" = "left";
  export let disabled: boolean = false;
  export let loading: boolean = false;
  export let onClick: (e?: any) => void = (e) => {};

  const handleClick = async (e: any) => {
    if (href) {
      if (target) window.open(href, target);
      else goto(href);
      return
    }
    if (disabled || loading) return;
    onClick(e);
  };

</script>

<button
  class="button {theme} {size} relative whitespace-nowrap {disabled ? 'disabled' : ''}"
  class:!bg-neutral-400={loading}
  class:!border-neutral-400={loading}
  class:!grayscale={disabled}
  class:!cursor-not-allowed={disabled}
  class:!text-neutral-700={disabled}
  on:click={handleClick}
  >
  {#if icon && iconPosition === "left"}
    <p class:opacity-0={loading}>
      <Icon icon={icon} class="w-[20px] h-[20px]" />
    </p>
  {/if}
  {#if loading}
    <Loading />
  {/if}
  <p class:opacity-0={loading}>
    <slot />
  </p>
  {#if icon && iconPosition === "right"}
    <p class:opacity-0={loading}>
      <Icon icon={icon} class="w-[20px] h-[20px]" />
    </p>
  {/if}
</button>

<style lang="scss">
  .button {
    @apply rounded-full outline-none border font-medium flex items-center justify-center gap-1.5 transition-all duration-200 cursor-pointer;
    &.lg {
      @apply px-6 py-3 text-base;
    }
    &.md {
      @apply px-5 py-2 text-sm;
    }
    &.light {
      @apply bg-white text-neutral-900 border-white;
    }
    &.pink {
      @apply bg-pink-500 text-white border-pink-500;
    }
    &.blue {
      @apply bg-blue-500 text-white border-blue-500;
    }
    &.dark {
      @apply bg-neutral-900 border-neutral-800 text-neutral-300;
    }
    &.red {
      @apply bg-red-500 text-white border-red-500;
    }
    &:hover {
      @apply brightness-125
    }
    &.disabled {
      &:hover {
        @apply brightness-100
      }
    }
  }
</style>