import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { getAccessToken, getEmbeddedConnectedWallet, usePrivy, useWallets, Google, Twitter, Discord } from "@privy-io/react-auth";
import Head from "next/head";
import { useBalance } from 'wagmi';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDiscord, faGoogle, faMeta, faTwitter, faXTwitter } from "@fortawesome/free-brands-svg-icons";
import { faAdd, faFileExport, faLink, faTrash, faUnlink, faWallet } from "@fortawesome/free-solid-svg-icons";
import { useSetActiveWallet } from "@privy-io/wagmi";
import { encodeFunctionData, parseAbi } from 'viem';
import { gameDataABI } from "./data";
import { arbitrumSepolia, baseSepolia } from "viem/chains";

export default function DashboardPage() {
  const [verifyResult, setVerifyResult] = useState(0);
  const [username, setUsername] = useState('');
  const [userId, setUserId] = useState(0);
  const [vaultData, setVaultData] = useState({ prehp: "0", vc: "0" });
  const [showPopup, setShowPopup] = useState(false);
  const [ticketAmount, setTicketAmount] = useState(1);
  const router = useRouter();

  const { ready, authenticated, user, logout, exportWallet, linkWallet, unlinkWallet, linkDiscord, unlinkDiscord, linkTwitter, unlinkTwitter, linkGoogle, unlinkGoogle } = usePrivy();
  const { wallets } = useWallets();

  const [activeWallet, setActiveWallet] = useState(user?.wallet?.address);
  const [activeWalletObj, setActiveWalletObj] = useState(wallets[0]);
  const [ticketsCount, setTicketsCount] = useState(0);

  const { data: balanceData } = useBalance({
    address: activeWallet as `0x${string}`,
    token: "0x22b6c31c2beb8f2d0d5373146eed41ab9ede3caf"
  });

  const balance = balanceData?.formatted;
  const token = balanceData?.symbol;


  function ToggleDiscord() {
    if (user?.discord) {
      unlinkDiscord(user?.discord.subject);
    } else {
      linkDiscord();
    }
  }

  function ToggleTwitter() {
    if (user?.twitter) {
      unlinkTwitter(user?.twitter.subject);
    } else {
      linkTwitter();
    }
  }

  function ToggleGoogle() {
    if (user?.google) {
      unlinkGoogle(user?.google.subject);
    } else {
      linkGoogle();
    }
  }
  async function handleWalletClick(address: string) {
    setActiveWallet(address);
    const url = `https://vps.playpoolstudios.com/metahunt/api/launcher/set_wallet.php?id=${user?.id}&wallet=${address}`;
    const response = await fetch(url);
    console.log(url);

    wallets.forEach((element) => {
      if (element.address == address) {
        setActiveWalletObj(element);
        element.switchChain(chainId);
      }
    });

  }


  useEffect(() => {
    if (ready && !authenticated) {
      router.push("/");
    }
    if (ready) {
      if (username == "-1") {
        console.log(user?.id);
        router.push("/logincomplete");
      }
    }
  }, [ready, authenticated, router, username]);

  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);
        } catch (error) {
          console.error("Error fetching username:", error);
        }
      }
    }

    async function fetchVaultData() {
      if (user?.id) {
        try {
          const response = await fetch(`https://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);
        }
      }
    }

    async function fetchUserId(){
      try {
        const response = await fetch(`https://vps.playpoolstudios.com/metahunt/api/launcher/get_user_id.php?username=${user?.id}`);
        const data = await response.text();
        setUserId(parseInt(data));
      } catch (error) {
        console.error('Error fetching user ID:', error);
        return null;
      }
    };

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

  async function autoSetActiveWallet(){
    try {
      const response = await fetch(`https://vps.playpoolstudios.com/metahunt/api/launcher/get_active_wallet.php?id=${user?.id}`);
      const activeWalletString = await response.text();
      wallets.forEach((element)=>{
        if(element.address == activeWalletString){
          setActiveWallet(element.address);
          setActiveWalletObj(element);
        }
      });

      if(activeWalletString != activeWallet){
        setActiveWalletObj(wallets[0]);
      }
    } catch (error) {
      console.error("Error fetching vault data:", error);
    }

  }

  const chainId = arbitrumSepolia.id;

  useEffect(() => {
    setActiveWallet(getEmbeddedConnectedWallet(wallets)?.address);
    autoSetActiveWallet();
    getTickets();
  }, [wallets]);

  useEffect(() => {
    getTickets();
  }, [activeWalletObj]);


  const contractAddress = "0x7e06ae145dc3d73350c7da040355654EbF11f1bc";
  async function buyTicket(amount: number) {
    const isEmbedded = getEmbeddedConnectedWallet(wallets)?.address == activeWalletObj?.address;
    const provider = await activeWalletObj?.getEthereumProvider();
    if (!provider) {
      console.error("Ethereum provider not found");
      return;
    }

    const data = encodeFunctionData({
      abi: gameDataABI,
      functionName: 'buyTickets',
      args: [amount],
    });
    const value = 1000000000000 * amount;
    console.log(`isEmbbedded : ${isEmbedded}`)
    const transactionRequest = {
      from: activeWalletObj?.address,
      to: contractAddress,
      data: data,
      value: isEmbedded ? value : value.toString(),
    };

    try {
      const transactionHash = await provider.request({
        method: 'eth_sendTransaction',
        params: [transactionRequest],
      });
      // Polling for the transaction receipt
    const checkTransactionReceipt = async () => {
      const receipt = await provider.request({
        method: 'eth_getTransactionReceipt',
        params: [transactionHash],
      });

      if (receipt && receipt.status) {
        if (receipt.status === '0x1') { // Transaction was successful
          console.log('Transaction confirmed:', receipt);
          getTickets(); // Call getTickets() after the transaction is confirmed
          //setShowPopup(false); // Close the popup after successful transaction
        } else {
          console.error('Transaction failed:', receipt);
        }
      } else {
        // Retry after some delay if the receipt is not available yet
        setTimeout(checkTransactionReceipt, 2000); // Poll every 2 seconds
      }
    };

    checkTransactionReceipt(); 
      setShowPopup(false); // Close the popup after successful transaction
    } catch (error) {
      console.error('Transaction failed:', error);
    }
  }

  async function getTickets() {
    const provider = await activeWalletObj?.getEthereumProvider();
    if (!provider) {
      console.error("Ethereum provider not found");
      return;
    }

    try {
      const data = encodeFunctionData({
        abi: gameDataABI,
        functionName: 'balanceOf',
        args: [activeWalletObj?.address, 0],
      });

      const callRequest = {
        from: activeWalletObj?.address,
        to: contractAddress,
        data: data,
      };

      const result = await provider.request({
        method: 'eth_call',
        params: [callRequest],
      });

      const balanceHex = result;
      const balance = parseInt(balanceHex, 16);
      setTicketsCount(balance);
    } catch (error) {
      console.error('Call failed:', error);
    }
  }

  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-gradient-to-br from-purple-900 to-blue-900 text-white">
        {ready && authenticated && userId >0 ? (
          <>
            <div className="flex flex-row justify-between items-center mb-8">
              <div className="flex items-center">
                <h1 className="text-3xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-cyan-400 to-blue-500 mr-2">
                  Welcome {username || "Crypto Warrior"}
                </h1>
                <a href={`https://testnets.opensea.io/assets/arbitrum-sepolia/0x5F018178AC0BDa64A89A9C446365c8BeBCA8dcc2/${userId}`} className="inline-block ml-6 w-8 h-8 bg-white rounded-full text-purple-900 font-bold text-sm flex items-center justify-center hover:bg-yellow-500 transition-colors duration-200">
                  <svg aria-label="OpenSea" className="w-5 h-5" viewBox="0 0 90 90" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path d="M45 0C20.151 0 0 20.151 0 45C0 69.849 20.151 90 45 90C69.849 90 90 69.849 90 45C90 20.151 69.858 0 45 0ZM22.203 46.512L22.392 46.206L34.101 27.891C34.272 27.63 34.677 27.657 34.803 27.945C36.756 32.328 38.448 37.782 37.656 41.175C37.323 42.57 36.396 44.46 35.352 46.206C35.217 46.458 35.073 46.71 34.911 46.953C34.839 47.061 34.713 47.124 34.578 47.124H22.545C22.221 47.124 22.032 46.773 22.203 46.512ZM74.376 52.812C74.376 52.983 74.277 53.127 74.133 53.19C73.224 53.577 70.119 55.008 68.832 56.799C65.538 61.38 63.027 67.932 57.402 67.932H33.948C25.632 67.932 18.9 61.173 18.9 52.83V52.56C18.9 52.344 19.08 52.164 19.305 52.164H32.373C32.634 52.164 32.823 52.398 32.805 52.659C32.706 53.505 32.868 54.378 33.273 55.17C34.047 56.745 35.658 57.726 37.395 57.726H43.866V52.677H37.467C37.143 52.677 36.945 52.299 37.134 52.029C37.206 51.921 37.278 51.813 37.368 51.687C37.971 50.823 38.835 49.491 39.699 47.97C40.284 46.944 40.851 45.846 41.31 44.748C41.4 44.55 41.472 44.343 41.553 44.145C41.679 43.794 41.805 43.461 41.895 43.137C41.985 42.858 42.066 42.57 42.138 42.3C42.354 41.364 42.444 40.374 42.444 39.348C42.444 38.943 42.426 38.52 42.39 38.124C42.372 37.683 42.318 37.242 42.264 36.801C42.228 36.414 42.156 36.027 42.084 35.631C41.985 35.046 41.859 34.461 41.715 33.876L41.661 33.651C41.553 33.246 41.454 32.868 41.328 32.463C40.959 31.203 40.545 29.97 40.095 28.818C39.933 28.359 39.753 27.918 39.564 27.486C39.294 26.82 39.015 26.217 38.763 25.65C38.628 25.389 38.52 25.155 38.412 24.912C38.286 24.642 38.16 24.372 38.025 24.111C37.935 23.913 37.827 23.724 37.755 23.544L36.963 22.086C36.855 21.888 37.035 21.645 37.251 21.708L42.201 23.049H42.219C42.228 23.049 42.228 23.049 42.237 23.049L42.885 23.238L43.605 23.436L43.866 23.508V20.574C43.866 19.152 45 18 46.413 18C47.115 18 47.754 18.288 48.204 18.756C48.663 19.224 48.951 19.863 48.951 20.574V24.939L49.482 25.083C49.518 25.101 49.563 25.119 49.599 25.146C49.725 25.236 49.914 25.38 50.148 25.56C50.337 25.704 50.535 25.884 50.769 26.073C51.246 26.46 51.822 26.955 52.443 27.522C52.605 27.666 52.767 27.81 52.92 27.963C53.721 28.71 54.621 29.583 55.485 30.555C55.728 30.834 55.962 31.104 56.205 31.401C56.439 31.698 56.7 31.986 56.916 32.274C57.213 32.661 57.519 33.066 57.798 33.489C57.924 33.687 58.077 33.894 58.194 34.092C58.554 34.623 58.86 35.172 59.157 35.721C59.283 35.973 59.409 36.252 59.517 36.522C59.85 37.26 60.111 38.007 60.273 38.763C60.327 38.925 60.363 39.096 60.381 39.258V39.294C60.435 39.51 60.453 39.744 60.471 39.987C60.543 40.752 60.507 41.526 60.345 42.3C60.273 42.624 60.183 42.93 60.075 43.263C59.958 43.578 59.85 43.902 59.706 44.217C59.427 44.856 59.103 45.504 58.716 46.098C58.59 46.323 58.437 46.557 58.293 46.782C58.131 47.016 57.96 47.241 57.816 47.457C57.609 47.736 57.393 48.024 57.168 48.285C56.97 48.555 56.772 48.825 56.547 49.068C56.241 49.437 55.944 49.779 55.629 50.112C55.449 50.328 55.251 50.553 55.044 50.751C54.846 50.976 54.639 51.174 54.459 51.354C54.144 51.669 53.892 51.903 53.676 52.11L53.163 52.569C53.091 52.641 52.992 52.677 52.893 52.677H48.951V57.726H53.91C55.017 57.726 56.07 57.339 56.925 56.61C57.213 56.358 58.482 55.26 59.985 53.604C60.039 53.541 60.102 53.505 60.174 53.487L73.863 49.527C74.124 49.455 74.376 49.644 74.376 49.914V52.812V52.812Z" />
                  </svg>
                </a>
              </div>
              <button
                onClick={logout}
                className="text-sm bg-gradient-to-r from-red-500 to-pink-500 hover:from-red-600 hover:to-pink-600 py-2 px-6 rounded-full text-white font-semibold transform hover:scale-105 transition duration-300 ease-in-out"
              >
                Logout
              </button>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
              <div className="bg-gradient-to-br from-purple-800 to-indigo-900 rounded-2xl p-6 shadow-lg hover:shadow-2xl transition duration-300 ease-in-out transform hover:-translate-y-1">
                <h2 className="text-lg font-semibold mb-2 text-purple-300">Vault Credits</h2>
                <p className="text-4xl font-bold text-white">{vaultData.vc || "0"} <span className="text-2xl text-purple-300">VC</span></p>
              </div>
              <div className="bg-gradient-to-br from-blue-800 to-cyan-900 rounded-2xl p-6 shadow-lg hover:shadow-2xl transition duration-300 ease-in-out transform hover:-translate-y-1">
                <h2 className="text-lg font-semibold mb-2 text-blue-300">{token} Balance</h2>
                <p className="text-4xl font-bold text-white">{balance || 0} <span className="text-2xl text-blue-300">{token}</span></p>
                <p className="text-xs mt-2 text-blue-300 truncate">{activeWallet}</p>
              </div>
              <div className="bg-gradient-to-br from-green-800 to-teal-900 rounded-2xl p-6 shadow-lg hover:shadow-2xl transition duration-300 ease-in-out transform hover:-translate-y-1 flex flex-col justify-between">
                <div>
                  <h2 className="text-lg font-semibold mb-2 text-green-300">Hunt Tickets</h2>
                  <p className="text-4xl font-bold text-white">{ticketsCount || "0"}</p>
                </div>
                <div className="flex justify-end">
                  <button
                    onClick={() => setShowPopup(true)}
                    className="bg-gradient-to-r from-green-500 to-teal-500 hover:from-green-600 hover:to-teal-600 py-2 px-4 rounded-full text-white font-semibold transform hover:scale-105 transition duration-300 ease-in-out"
                  >
                    Buy Tickets
                  </button>
                </div>
              </div>
              <div className="bg-gradient-to-br from-yellow-800 to-orange-900 rounded-2xl p-6 shadow-lg hover:shadow-2xl transition duration-300 ease-in-out transform hover:-translate-y-1">
                <h2 className="text-lg font-semibold mb-2 text-yellow-300">Pre-hunt Points</h2>
                <p className="text-4xl font-bold text-white">{vaultData.prehp || "0"} <span className="text-2xl text-yellow-300">PHP</span></p>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 mt-10">
              <div className="bg-gradient-to-br from-gray-900 to-gray-800 rounded-3xl shadow-xl p-8">
                <h2 className="text-2xl font-bold mb-6 text-center text-transparent bg-clip-text bg-gradient-to-r from-purple-400 to-pink-500">Socials</h2>
                <div className="space-y-6">
                  {[
                    { icon: faXTwitter, name: 'Twitter', user: user?.twitter, toggle: ToggleTwitter },
                    { icon: faDiscord, name: 'Discord', user: user?.discord, toggle: ToggleDiscord },
                    { icon: faGoogle, name: 'Google', user: user?.google, toggle: ToggleGoogle }
                  ].map((social) => (
                    <div key={social.name} className="flex flex-col sm:flex-row items-start sm:items-center justify-between bg-gray-800 rounded-xl p-4 hover:bg-gray-700 transition duration-300">
                      <div className="flex items-center space-x-4 mb-2 sm:mb-0">
                        <div className="w-8 h-8 flex items-center justify-center">
                          <FontAwesomeIcon icon={social.icon} size="2x" className="text-blue-400" />
                        </div>
                        <span className="font-medium">{social.name}</span>
                      </div>
                      <div className="flex flex-col sm:flex-row items-start sm:items-center space-y-2 sm:space-y-0 sm:space-x-4 w-full sm:w-auto">
                        <span className={`px-3 py-1 rounded-full ${social.user ? 'bg-green-900 text-green-300' : 'bg-gray-700 text-gray-400'} text-sm sm:text-base truncate max-w-full sm:max-w-[200px]`}>
                          {social.user ? (
                            social.name === 'Google' 
                              ? `@${(social.user as Google).email}` 
                              : `@${(social.user as Twitter | Discord).username}`
                          ) : 'Not linked'}
                        </span>
                        <button
                          onClick={social.toggle}
                          className={`rounded-full px-4 py-2 font-semibold transition duration-300 w-full sm:w-auto ${
                            social.user
                              ? 'bg-red-600 hover:bg-red-700 text-white'
                              : 'bg-green-600 hover:bg-green-700 text-white'
                          }`}
                        >
                          {social.user ? 'Unlink' : 'Link'}
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="bg-gradient-to-br from-gray-900 to-gray-800 rounded-3xl shadow-xl p-8">
                <h2 className="text-2xl font-bold mb-6 text-center text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-cyan-500">Wallets</h2>
                <div className="space-y-4">
                  <div
                    className={`grid grid-cols-6 ${
                      activeWallet == getEmbeddedConnectedWallet(wallets)?.address
                        ? 'bg-gradient-to-r from-blue-700 to-purple-700'
                        : 'bg-gray-800'
                    } rounded-xl p-4 items-center cursor-pointer transition duration-300 hover:shadow-lg`}
                    onClick={() => handleWalletClick(getEmbeddedConnectedWallet(wallets)?.address ?? "")}
                  >
                    <FontAwesomeIcon icon={faLink} className="text-cyan-400 w-8 h-8" />
                    <div className="col-span-4">
                      <p className="font-semibold">W3B Wallet</p>
                      <p className="text-sm text-gray-400 truncate">
                        {getEmbeddedConnectedWallet(wallets)?.address}
                      </p>
                    </div>
                    <button
                      className="justify-self-end bg-purple-600 hover:bg-purple-700 rounded-full p-2 transition duration-300"
                      onClick={exportWallet}
                    >
                      <FontAwesomeIcon icon={faFileExport} className="w-4 h-4" />
                    </button>
                  </div>

                  {wallets.map((wallet) => {
                    if (wallet.connectorType == "embedded") return null;
                    const address = wallet.address;
                    return (
                      <div
                        key={address}
                        className={`grid grid-cols-6 ${
                          wallet.linked
                            ? address == activeWallet
                              ? 'bg-gradient-to-r from-blue-700 to-purple-700'
                              : 'bg-gray-800'
                            : 'bg-gray-900 bg-opacity-30'
                        } rounded-xl p-4 items-center cursor-pointer transition duration-300 hover:shadow-lg`}
                        onClick={() => handleWalletClick(address)}
                      >
                        <FontAwesomeIcon icon={faWallet} className={`${wallet.linked ? 'text-yellow-400' : 'text-gray-600'} w-8 h-8`} />
                        <div className="col-span-4">
                          <p className={`font-semibold ${wallet.linked ? 'text-white' : 'text-gray-600'}`}>{wallet.walletClientType}</p>
                          <p className={`text-sm ${wallet.linked ? 'text-gray-300' : 'text-gray-600'} truncate`}>{wallet.address}</p>
                        </div>
                        {wallet.linked ? (
                          <button
                            className="justify-self-end bg-red-600 hover:bg-red-700 rounded-full p-2 transition duration-300"
                            onClick={() => unlinkWallet(wallet.address)}
                          >
                            <FontAwesomeIcon icon={faUnlink} className="w-4 h-4" />
                          </button>
                        ) : (
                          <FontAwesomeIcon icon={faUnlink} className="w-4 h-4 text-gray-600 justify-self-end" />
                        )}
                      </div>
                    );
                  })}

                  <button
                    onClick={linkWallet}
                    className="bg-gradient-to-r from-green-500 to-blue-500 hover:from-green-600 hover:to-blue-600 text-white font-bold py-2 px-3 rounded-lg transition duration-300 ease-in-out flex items-center justify-center space-x-2 text-sm"
                  >
                    <FontAwesomeIcon icon={faAdd} className="w-4 h-4" />
                    <span>Connect New Wallet</span>
                  </button>
                </div>
              </div>
            </div>

            {showPopup && (
              <div className="fixed inset-0 bg-black bg-opacity-75 flex justify-center items-center z-50">
                <div className="bg-gradient-to-br from-gray-900 to-gray-800 p-8 rounded-2xl shadow-2xl max-w-md w-full">
                  <h2 className="text-2xl font-bold mb-6 text-center text-transparent bg-clip-text bg-gradient-to-r from-green-400 to-blue-500">Buy Hunt Tickets</h2>
                  <div className="flex items-center justify-center space-x-4 mb-6">
                    <button
                      onClick={() => setTicketAmount(Math.max(1, ticketAmount - 1))}
                      className={`text-2xl bg-gray-700 hover:bg-gray-600 text-white w-12 h-12 rounded-full transition duration-300 ${ticketAmount <= 1 ? 'opacity-50 cursor-not-allowed' : ''}`}
                      disabled={ticketAmount <= 1}
                    >
                      -
                    </button>
                    <div className="w-24 text-center text-2xl font-bold text-white bg-transparent border-b-2 border-blue-500">
                      {ticketAmount}
                    </div>
                    <button
                      onClick={() => setTicketAmount(ticketAmount + 1)}
                      className="text-2xl bg-gray-700 hover:bg-gray-600 text-white w-12 h-12 rounded-full transition duration-300"
                    >
                      +
                    </button>
                  </div>
                  <div className="flex justify-between space-x-4">
                    <button
                      onClick={() => buyTicket(ticketAmount)}
                      className="flex-1 bg-gradient-to-r from-green-500 to-blue-500 hover:from-green-600 hover:to-blue-600 text-white font-bold py-3 px-6 rounded-full transition duration-300 ease-in-out transform hover:scale-105"
                    >
                      Buy Tickets
                    </button>
                    <button
                      onClick={() => setShowPopup(false)}
                      className="flex-1 bg-gradient-to-r from-red-500 to-pink-500 hover:from-red-600 hover:to-pink-600 text-white font-bold py-3 px-6 rounded-full transition duration-300 ease-in-out transform hover:scale-105"
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              </div>
            )}
          </>
        ) : (
          <div className="flex justify-center items-center h-screen">
            <div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
          </div>
        )}
      </main>
    </>
  );
}
