"use client";
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import axios from 'axios';
import { usePrivy } from '@privy-io/react-auth';
import Link from 'next/link';
import Button from '../components/LoginButton';
import Head from 'next/head';

const Home: React.FC = () => {
    const { login, ready, user } = usePrivy();
    const router = useRouter(); //
    useEffect(() => {

        const setResult = async (result: string, wallet: string) => {
            const params = new URLSearchParams(window.location.search);
            const requestIdFromUrl = params.get('request_id');

            if (!result.includes('privy')) {
                return;
            }
            try {

                //Get username from database
                const response = await fetch(`https://vps.playpoolstudios.com/metahunt/api/launcher/get_display_name_public.php?id=${user?.id}`);
                const databaseUsername = await response.text();

                if (databaseUsername == "-1") {
                    console.log(user?.id);
                    router.push("/logincomplete?request_id=" + requestIdFromUrl);
                    return;
                }

                await axios({
                    method: 'get',
                    url: `https://vps.playpoolstudios.com/metahunt/api/launcher/set_request_response.php`,
                    withCredentials: false,
                    params: {
                        id: requestIdFromUrl,
                        result: result
                    },
                });
                console.log(`https://vps.playpoolstudios.com/metahunt/api/launcher/set_request_response.php?id=${requestIdFromUrl}&result=${result}`);
                await axios({
                    method: 'get',
                    url: `https://vps.playpoolstudios.com/metahunt/api/launcher/set_wallet.php`,
                    withCredentials: false,
                    params: {
                        id: result,
                        wallet: wallet,
                        init: "true"
                    },
                });
            } catch (error) {
                console.error('Error making GET request:', error);
            }
        };

        const requestIdFromUrl = new URLSearchParams(window.location.search).get('request_id');

        if (!ready) {
            console.log("not ready yet");
        }
        else if (requestIdFromUrl) {
            setResult(user?.id ?? "", user?.wallet?.address ?? "no wallet"); // Replace 'some_result' with the actual result you want to send
        }
    }, [ready, user]);

    return (
        
        <div className='font-inter'>
            <Head>
        <title>Link W3B Launcher · W3B Games</title>
        <link
          href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
          rel="stylesheet"
        />
      </Head>
        <div className="flex flex-col w-full h-screen">
          <div className="flex-[2] bg-[#0F0F0F]"></div>
          <div className="flex-[5] bg-black"></div>
        </div>
        <div className="absolute inset-x-0 top-0 flex items-center justify-center pointer-events-none h-[57.2vh]">
          <h2 className="text-[10vw] font-bold whitespace-nowrap bg-clip-text text-transparent bg-[linear-gradient(to_bottom,black_50%,#0F0F0F_50%)]">METAHUNT</h2>
        </div>
        <div className="absolute inset-x-10 top-10 flex w-24 h-24">
          <img src="./logos/logo.png"/>
        </div>
        <div className="absolute inset-0 flex justify-center items-center">
        <div className='flex items-center justify-center h-screen text-white'>
            {user && ready ? (
                <div className='justify-center flex flex-col items-center bg-black bg-opacity-30 p-8 rounded-xl backdrop-blur-md shadow-lg'>
                    <h1 className='text-4xl font-bold mb-6 text-white/80'>Login Successful!</h1>
                    <p className='mb-6 text-lg text-gray-300'>Your W3B Launcher is now securely connected.</p>
                    <Button onClick={()=>{router.push("/dashboard");}} text='Enter Dashboard'/>
                </div>
            ) : (
                <div className="flex flex-col items-center justify-center">
                    <h1 className="text-4xl font-bold mb-6 text-white/80">Link your W3B Games Launcher</h1>
                    {/* <p className="mb-6 text-lg text-gray-300">Connect your crypto wallet to access the W3B Games ecosystem</p> */}
                    <Button onClick={login} text="LOG IN / REGISTER" />
                </div>
            )}
        </div>
        </div>
    </div>
    );
};

export default Home;
