import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { getAccessToken, usePrivy } from "@privy-io/react-auth";
import Head from "next/head";
import { useBalance } from 'wagmi';

async function verifyToken() {
  const url = "/api/verify";
  const accessToken = await getAccessToken();
  const result = await fetch(url, {
    headers: {
      ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined),
    },
  });

  return await result.json();
}

export default function DashboardPage() {
  const [verifyResult, setVerifyResult] = useState(0);
  const [username, setUsername] = useState('');
  const [vaultData, setVaultData] = useState({ prehp: "0", vc: "0" });
  const router = useRouter();

  const { ready, authenticated, user, logout, linkTwitter, unlinkTwitter, unlinkDiscord, linkDiscord, unlinkWallet, linkWallet } = usePrivy();
  const { data: balanceData } = useBalance({
    address: user?.wallet?.address as `0x${string}`,
  });
  const balance = balanceData?.formatted;
  const token = balanceData?.symbol;

  useEffect(() => {
    if (ready && !authenticated) {
      router.push("/");
    }
  }, [ready, authenticated, router]);

  useEffect(() => {
    async function fetchUsername() {
      if (ready) {
        try {
          const response = await fetch(`https://vps.playpoolstudios.com/metahunt/api/launcher/get_display_name_public.php?id=${user?.id}`);
          const data = await response.text();
          setUsername(data); // Assuming the response contains the display name under `display_name`
        } catch (error) {
          console.error("Error fetching username:", error);
        }
      }
    }

    async function fetchVaultData() {
      if (user?.id) {
        try {
          const response = await fetch(`http://vps.playpoolstudios.com/metahunt/api/launcher/get_vault.php?id=${user?.id}`);
          const data = await response.json();
          setVaultData({ prehp: data.prehp, vc: data.vc });
        } catch (error) {
          console.error("Error fetching vault data:", error);
        }
      }
    }

    fetchUsername();
    fetchVaultData();
  }, [ready]);

  const numAccounts = user?.linkedAccounts?.length || 0;
  const canRemoveAccount = numAccounts > 1;

  const email = user?.email;
  const phone = user?.phone;
  const wallet = user?.wallet;

  const googleSubject = user?.google?.subject || null;
  const twitterSubject = user?.twitter?.subject || null;
  const discordSubject = user?.discord?.subject || null;

  return (
    <>
      <Head>
        <title>W3B Games Dashboard</title>
      </Head>

      <main className="flex flex-col min-h-screen px-4 sm:px-20 py-6 sm:py-10 bg-black text-white">
        {ready && authenticated ? (
          <>
            <div className="flex flex-row justify-between">
              <h1 className="text-2xl font-semibold text-white">Welcome {username || "User"},</h1>
              <button
                onClick={logout}
                className="text-sm bg-red-500 hover:bg-red-700 py-2 px-4 rounded-md text-violet-100"
              >
                Logout
              </button>
            </div>
            <div className="flex flex-wrap items-center justify-center">
              <div className="items-center justify-center p-20">
                <h1 className="text-s">Vault Credits</h1>
                <h1 className="text-4xl flex justify-center">{vaultData.vc || "0"} VC</h1>
              </div>
              <div className="items-center justify-center p-20">
                <h1 className="text-xs">{user?.wallet?.address}</h1>
                <h1 className="text-4xl flex justify-center">{balance || 0} {token}</h1>
              </div>
              <div className="items-center justify-center p-20">
                <h1 className="text-s">Pre-hunt Points</h1>
                <h1 className="text-4xl flex justify-center">{vaultData.prehp || "0"} PHP</h1>
              </div>
            </div>
            
            <div className="mt-12 flex gap-4 flex-wrap">
              {twitterSubject ? (
                <button
                  onClick={() => {
                    unlinkTwitter(twitterSubject);
                  }}
                  className="text-sm border border-violet-600 hover:border-violet-700 py-2 px-4 rounded-md text-violet-600 hover:text-violet-700 disabled:border-gray-500 disabled:text-gray-500 hover:disabled:text-gray-500"
                  disabled={!canRemoveAccount}
                >
                  Unlink Twitter
                </button>
              ) : (
                <button
                  className="text-sm bg-violet-600 hover:bg-violet-700 py-2 px-4 rounded-md text-white"
                  onClick={() => {
                    linkTwitter();
                  }}
                >
                  Link Twitter
                </button>
              )}

              {discordSubject ? (
                <button
                  onClick={() => {
                    unlinkDiscord(discordSubject);
                  }}
                  className="text-sm border border-violet-600 hover:border-violet-700 py-2 px-4 rounded-md text-violet-600 hover:text-violet-700 disabled:border-gray-500 disabled:text-gray-500 hover:disabled:text-gray-500"
                  disabled={!canRemoveAccount}
                >
                  Unlink Discord
                </button>
              ) : (
                <button
                  className="text-sm bg-violet-600 hover:bg-violet-700 py-2 px-4 rounded-md text-white"
                  onClick={() => {
                    linkDiscord();
                  }}
                >
                  Link Discord
                </button>
              )}
              {wallet ? (
                <button
                  onClick={() => {
                    unlinkWallet(wallet.address);
                  }}
                  className="text-sm border border-violet-600 hover:border-violet-700 py-2 px-4 rounded-md text-violet-600 hover:text-violet-700 disabled:border-gray-500 disabled:text-gray-500 hover:disabled:text-gray-500"
                  disabled={!canRemoveAccount}
                >
                  Unlink wallet
                </button>
              ) : (
                <button
                  onClick={linkWallet}
                  className="text-sm bg-violet-600 hover:bg-violet-700 py-2 px-4 rounded-md text-white border-none"
                >
                  Connect wallet
                </button>
              )}
              <button onClick={linkWallet}>
                Wallet
              </button>
            </div>
          </>
        ) : null}
      </main>
    </>
  );
}
