import {
	ConnectButton,
	useCurrentAccount,
	useSignAndExecuteTransactionBlock,
	useSuiClient,
} from "@mysten/dapp-kit";
import { CoinBalance } from "@mysten/sui.js/client";
import { MIST_PER_SUI } from "@mysten/sui.js/utils";
import { useEffect, useState } from "react";
import Votes from "./components/Votes";

const balanceToSui = (balance: CoinBalance) => {
	return Number.parseInt(balance.totalBalance) / Number(MIST_PER_SUI);
};

// const mistToSui = (amountInMist: string) => {
// 	return Number.parseInt(amountInMist) / Number(MIST_PER_SUI);
// };

export default function App() {
	const suiClient = useSuiClient();
	const currentAccount = useCurrentAccount();
	const { mutate: signAndExecuteTransactionBlock } =
		useSignAndExecuteTransactionBlock();

	const [balance, setBalance] = useState("(loading...)");

	useEffect(() => {
		(async () => {
			if (currentAccount) {
				const balance = await suiClient.getBalance({
					owner: currentAccount.address,
				});
				setBalance(`Balance: ${balanceToSui(balance)} SUI`);
			}
		})();
	}, [suiClient, currentAccount]);

	return (
		<>
			<h1>Afet Destek</h1>

			<div>{balance}</div>

			<ConnectButton />

			<button
				onClick={async () => {
					console.log(
						await suiClient.getObject({
							id: "0x900ad4444942b20a9c2ac1f3949afbd4cfa89e3d19e6286a21be7b48fd5d2323",
							options: {
								showContent: true,
								showType: true,
							},
						})
					);
				}}
			>
				try getting object
			</button>

			{/* {currentAccount && (
				<>
					<div>
						<button
							onClick={() => {
								const txb = new TransactionBlock();

								txb.moveCall({
									target: "0x079072d66290a6f50781126e05528c531757cc63a9ddcc90a602c9488969c478::hackathon::fund::vote",
								});

								signAndExecuteTransactionBlock(
									{
										transactionBlock: new TransactionBlock(),
										chain: "sui:testnet",
									},
									{
										onSuccess: (result) => {
											console.log("executed transaction block", result);
											console.log(result.digest);
										},
										onError: (error) => {
											console.log("error", error);
										},
									}
								);
							}}
						>
							Sign and execute transaction block
						</button>
					</div>
				</>
			)} */}

			<Votes />
		</>
	);
}
