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

export default function LoginComplete() {
  const [username, setUsername] = useState("");
  const [error, setError] = useState(""); 
  const {ready, user,authenticated} = usePrivy();
  const router = useRouter();
  const handleUsernameChange = (e: { target: { value: SetStateAction<string>; }; }) => {
    setUsername(e.target.value);
    setError("");
  };

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

  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") {
        await fetch(
          `https://vps.playpoolstudios.com/metahunt/api/web/set_username.php?id=${user?.id}&username=${username}`
        );
        // Optionally, handle successful username set
        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="bg-black h-screen text-white">
        <div className="flex justify-center items-center h-full flex-col">
          <p className="text-3xl pb-10">Let's Complete your Login</p>
          <p>Enter your unique username</p>
          <form className="flex flex-col">
            <input
              type="text"
              name="username"
              value={username}
              onChange={handleUsernameChange}
              placeholder="ex: John123"
              className="bg-gray-900 rounded-full w-96 my-2"
            />
          </form>
          {error && <p className="text-red-500 mt-4">{error}</p>}
          <button
            className="bg-green-700 rounded-full mx-10 h-12 w-48"
            onClick={handleClaim}
          >
            Claim
          </button>
          
        </div>
      </div>
    </>
  );
}
