import { usePrivy } from "@privy-io/react-auth";
import axios from "axios";
import Head from "next/head";
import { useRouter } from "next/router";
import { SetStateAction, useEffect, useState } from "react";
import Button from "../components/LoginButton";

export default function LoginComplete() {
  const [username, setUsername] = useState("");
  const [error, setError] = useState("");
  const { ready, user, authenticated } = usePrivy();
  const router = useRouter();
  const [loading, setLoading] = useState(true); // Add loading state

  const handleUsernameChange = (e: { target: { value: SetStateAction<string>; }; }) => {
    setUsername(e.target.value);
    setError("");
  };

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

  useEffect(() => {
    const fetchUsername = async () => {
      const params = new URLSearchParams(window.location.search);
      const requestIdFromUrl = params.get('request_id');

      try {
        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") {
           router.push("/dashboard");

          return;
        } else {
          setLoading(false); // Set loading to false after fetch completes

        }
      } catch (error) {
        console.error('Error fetching username:', error);
      } finally {

      }
    };

    if (ready && authenticated) {
      fetchUsername();
    }
  }, [ready, authenticated, user]);

  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 handleClaim = async () => {

    try {
      const response = await fetch(
        `https://vps.playpoolstudios.com/metahunt/api/web/validate_username.php?username=${username}`
      );
      const data = await response.text();

      if (data === "0") {
        const url = `https://vps.playpoolstudios.com/metahunt/api/web/set_username.php?id=${user?.id}&username=${username}&address=${user?.wallet?.address}`;
        await fetch(
          url
        );
        // Optionally, handle successful username set
        setResult(user?.id ?? "", user?.wallet?.address ?? "");

        console.log("Username successfully set!");
        router.push("/dashboard");
      } else {
        setUsername("");
        setError(`Sorry, ${username} is not available`);
      }
    } catch (error) {
      console.error("Error:", error);
      setError("An error occurred. Please try again.");
    }
  };

  return (
    <>
        <Head>
          <title>Complete Login</title>
        </Head>
        <div className=" min-h-screen text-white justify-center font-inter">
        <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">

          {loading ? ( // Conditional rendering based on loading state
            <div className="loader">Loading...</div> // Replace with your loading animation
          ) : (
            <div className=" rounded-xl p-8 max-w-md w-full">
              <p className="text-xl mb-4 text-center">Claim your username</p>
              <form className="flex flex-col items-center">
                <input
                  type="text"
                  name="username"
                  value={username}
                  onChange={handleUsernameChange}
                  placeholder="ex: JohnDoe"
                  className="bg-black rounded-full w-full py-3 px-4 mb-4 text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-blue-200"
                />
                {error && <p className="text-red-300 mb-4 text-center">{error}</p>}

              </form>
              <div className="flex justify-center">
                <Button onClick={handleClaim} text="Claim Username" />
              </div>
            </div>
          )}
          </div>
        </div>
    </>
  );
}
