import React, { useState } from 'react';
import type { ISolana } from '@dynamic-labs/solana-core';
import { isSolanaWallet } from '@dynamic-labs/solana-core';
import { useDynamicContext } from '@dynamic-labs/sdk-react-core';
import type { Connection } from '@solana/web3.js';
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';

function LegacyTransaction() {
    const [address, setAddress] = useState('');
    const [amount, setAmount] = useState('');
    const { primaryWallet } = useDynamicContext();

    const sendTransaction = async () => {

        if(!primaryWallet || !isSolanaWallet(primaryWallet)) {
        return;
        }

        const connection: Connection = await primaryWallet.getConnection();
        const cluster = connection.rpcEndpoint.includes('devnet') ? 'devnet' : 'mainnet';

        const fromKey = new PublicKey(primaryWallet.address);
        const toKey = new PublicKey(address);

        const amountInLamports = Number(amount) * 1000000000;
        const transferTransaction = new Transaction().add(
        SystemProgram.transfer({
            fromPubkey: fromKey,
            lamports: amountInLamports,
            toPubkey: toKey,
        }),
        );
        const blockhash = await connection.getLatestBlockhash();
        transferTransaction.recentBlockhash = blockhash.blockhash;
        transferTransaction.feePayer = fromKey;

        const signer: ISolana = await primaryWallet.getSigner();

        await signer
        .signAndSendTransaction(transferTransaction)
        .then((value: { signature: string }) => {
            console.log(
            `Transaction successful: https://solscan.io/tx/${value.signature}?cluster=${cluster}`,
            );
        })
        .catch((error: Error) => {
            console.error(error);
        });
    }

    return (
        <div>
            <h1>Legacy Transaction</h1>
                <input type="text" placeholder="Address" value={address} onChange={(e) => setAddress(e.target.value)} />
                <input type="text" placeholder="Amount" value={amount} onChange={(e) => setAmount(e.target.value)} />
                <button type="button" onClick={() => sendTransaction()}>Send Transaction</button>

        </div>
    )
}

export default LegacyTransaction;