<script lang="ts">
  import Button from "$lib/components/Button.svelte";
  import type { InputType } from "@breeztech/breez-sdk-liquid/web";
  import { walletState } from "$lib/wallet.svelte";
  import { PaymentStatus } from "portalbtc-lib";

  let { open = $bindable() }: { open: boolean } = $props();

  let destination = $state("");

  let amountSat = $state<number | "">("");
  let status = $state("");
  let isBolt11 = $state(false);

  let requireAmount = $state(false);

  $effect(() => {
    (async () => {
      isBolt11 = false;
      if (!destination.trim()) {
        requireAmount = false;
        return;
      }
      try {
        if (!$walletState.open) return;
        const parsed: InputType =
          await $walletState.wallet.parsePayment(destination);
        if (
          parsed.type === "bolt11" &&
          parsed.invoice.amountMsat !== undefined &&
          parsed.invoice.amountMsat > 0
        ) {
          requireAmount = false;
          amountSat = Math.floor(parsed.invoice.amountMsat / 1000);
          isBolt11 = true;
        } else {
          requireAmount = true;
        }
      } catch {
        requireAmount = true;
      }
    })();
  });

  let dialogEl: HTMLDialogElement;

  async function handleSend() {
    if (!$walletState.open) throw new Error("Wallet not open");
    const sendGenerator = $walletState.wallet.pay(
      destination,
      Number(amountSat) || 0,
    );
    for await (const {
      status: sendStatus,
      error: sendError,
    } of sendGenerator) {
      if (sendError && sendStatus !== PaymentStatus.CashuPaymentFailed)
        return alert(sendError);
      switch (sendStatus) {
        case PaymentStatus.ParsingDestination:
          status = "Parsing destination...";
          break;
        case PaymentStatus.AttemptingCashuPayment:
          status = "Attempting cashu payment...";
          break;
        case PaymentStatus.AttemptingLightningPayment:
          status = "Attempting lightning payment...";
          break;
        case PaymentStatus.CashuPaymentFailed:
          status = "Cashu payment failed";
          break;
        case PaymentStatus.AmountRequired:
          status = "Amount required";
          break;
        case PaymentStatus.PreparingOnchainPayment:
          status = "Preparing onchain payment...";
          break;
        case PaymentStatus.BroadcastingOnchainPayment:
          status = "Broadcasting onchain payment...";
          break;
        case PaymentStatus.PaymentFailed:
          status = "Payment failed";
          break;
        case PaymentStatus.PaymentSent:
          status = "Payment sent";
          break;
        default:
          status = "Unknown status";
          break;
      }
    }

    setTimeout(closeDialog, 1500);
  }

  $effect(() => {
    if (open) {
      status = "";
      destination = "";
      amountSat = "";
      dialogEl.showModal();
    } else dialogEl.close();
  });

  function closeDialog() {
    open = false;
  }
</script>

<dialog bind:this={dialogEl} onclose={() => (open = false)}>
  <button class="close" onclick={closeDialog}>&times;</button>
  <div class="content">
    <h3>Send</h3>

    <label>
      Destination
      <input
        type="text"
        bind:value={destination}
        placeholder="bolt12 / invoice / liquid / bitcoin address"
        required
      />
    </label>

    {#if requireAmount}
      <label>
        Amount (sats)
        <input
          type="number"
          min="0"
          step="1"
          bind:value={amountSat}
          placeholder="amount in sats"
        />
      </label>
    {:else if isBolt11}
      <p>Paying {amountSat} sats</p>
    {/if}

    {#if status}
      <p class="status">{status}</p>
    {/if}

    <div class="actions">
      <Button variant="primary" onclick={handleSend} disabled={!destination}>
        Send
      </Button>
      <Button onclick={closeDialog}>Cancel</Button>
    </div>
  </div>
</dialog>

<style>
  .close {
    position: absolute;
    top: 0.5rem;
    right: 0.8rem;
    background: none;
    border: none;
    font-size: 1.5rem;
    color: var(--accent-color);
    cursor: pointer;
  }

  .content {
    display: flex;
    flex-direction: column;
  }

  h3 {
    font-size: 1.2rem;
    color: var(--accent-color);
    margin-bottom: 1.5rem;
    text-shadow: 2px 2px 0 #000;
    letter-spacing: 2px;
  }
  label {
    display: flex;
    flex-direction: column;
    font-size: 0.8rem;
    margin-bottom: 1rem;
  }
  input {
    margin-top: 0.4rem;
    font-family: inherit;
    font-size: 0.9rem;
    padding: 0.4rem 0.6rem;
    border: 2px solid var(--accent-color);
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.2);
    color: var(--text-color);
  }
  .status {
    margin: 0.5rem 0 1rem;
    font-size: 0.7rem;
    color: var(--accent-color);
  }
  .actions {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
  }
</style>
