import { FC, FormEventHandler, useState } from 'react';
import { Transaction } from '@mysten/sui/transactions';
import { useDynamicContext } from '@dynamic-labs/sdk-react-core';
import { isSuiWallet } from '@dynamic-labs/sui';

const MIST_PER_SUI = 1_000_000_000;

export const SendTransactionSection: FC = () => {
  const { primaryWallet } = useDynamicContext();

  const [txSignature, setTxSignature] = useState('');

  if (!primaryWallet || !isSuiWallet(primaryWallet)) return null;

  const onSubmit: FormEventHandler<HTMLFormElement> = async (event) => {
    event.preventDefault();

    const formData = new FormData(event.currentTarget);

    const address = formData.get('address') as string;
    const amount = Number(formData.get('amount')) * MIST_PER_SUI;

    const walletClient = await primaryWallet.getWalletClient();

    const tx = new Transaction();
    tx.setSender(primaryWallet.address);
    tx.setGasPrice(1_000);
    tx.setGasBudget(10_000_000);

    // Split the gas coin to create a new coin with the specified amount
    const [coin] = tx.splitCoins(tx.gas, [amount]);

    // Transfer the new coin to the recipient
    tx.transferObjects([coin], address);

    const signedTransaction = await primaryWallet.signTransaction(tx);

    const executionResult = await walletClient?.executeTransactionBlock({
      options: {},
      signature: signedTransaction.signature,
      transactionBlock: signedTransaction.bytes,
    });

    console.log(executionResult);

    setTxSignature(
      executionResult?.digest || 'No transaction digest found'
    );
  };

  return (
    <form onSubmit={onSubmit}>
      <p>Send to SUI address</p>
      <input name="address" type="text" required placeholder="Address" />
      <input name="amount" type="text" required placeholder="0.01" />
      <button type="submit">Send</button>
      <p data-testid="transaction-section-result">{txSignature}</p>
    </form>
  );
};