import { useCopyToClipboard } from "@uidotdev/usehooks";
import type { ReactElement } from "react";
import { useState } from "react";

import { SocketScanIcon, Twitter } from "@components/common/Icons";
import { ModalHeader } from "@components/common/ModalHeader";
import { SlideInPanel } from "@components/common/SlideInPanel";
import { useSocketScanLink } from "@hooks/useSocketScanLink";

export const Share = ({
	isVisible,
	closePanel,
	txHash,
}: {
	isVisible: boolean;
	closePanel: () => void;
	txHash: string;
}) => {
	return (
		<SlideInPanel closePanel={closePanel} isVisible={isVisible}>
			<div className="bn-flex bn-flex-col bn-overflow-hidden">
				<ModalHeader label="Share Transaction" closeModal={closePanel} />
				<div className="bn-p-4 bn-flex bn-flex-col bn-space-y-5">
					<ShareToTwitter />
					<CopySocketScanLink txHash={txHash} />
				</div>
			</div>
		</SlideInPanel>
	);
};

const Item = ({ icon, label }: { icon: ReactElement; label: string }) => {
	return (
		<div className="bn-flex bn-items-center bn-space-x-2">
			{icon}
			<span className="bn-font-medium bn-text-primary bn-text-base">{label}</span>
		</div>
	);
};

const btnStyle =
	"bn-bg-transparent bn-p-0 bn-outline-none w-full bn-border-none bn-cursor-pointer";

const CopySocketScanLink = ({ txHash }: { txHash: string }) => {
	const { socketScanLink } = useSocketScanLink({ txHash, type: "tx" });
	const [_, copyToClipboard] = useCopyToClipboard();
	const [isCopied, setIsCopied] = useState(false);

	const handleCopy = () => {
		copyToClipboard(socketScanLink);
		setIsCopied(true);
		setTimeout(() => setIsCopied(false), 2000); // Reset after 2 seconds
	};

	return (
		<button type="button" onClick={handleCopy} className={btnStyle}>
			<Item
				icon={<SocketScanIcon height={32} width={32} />}
				label={isCopied ? "Copied!" : "Copy SocketScan Link"}
			/>
		</button>
	);
};

const ShareToTwitter = () => {
	function tweetAboutBungee() {
		const quote =
			bungeeFortune?.[Math.floor(Math.random() * bungeeFortune?.length)];

		const tweetText = quote.concat(
			"\n\n",
			"You should try: https://bungee.exchange/ @BungeeExchange",
		);
		const encodedTweetText = encodeURIComponent(tweetText);

		const twitterUrl = "https://twitter.com/intent/tweet?text=".concat(
			encodedTweetText,
		);
		window.open(twitterUrl, "_blank");
	}

	return (
		<button type="button" onClick={tweetAboutBungee} className={btnStyle}>
			<Item icon={<Twitter />} label="Share to Twitter" />
		</button>
	);
};

const bungeeFortune = [
	"Greatest treasures for you await on a new L2. Make the Jump!",
	"Those who don't jump will never fly",
	"Take the time to Refuel, an empty tank will take you nowhere",
	"Never thought Bungee Jumping would be so much fun!",
	"Fortune favors the bold - and the Bungee Jumpers",
	"When did bridging get so cheap?",
	"Wow that was fast",
];
