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-gradient-to-br from-purple-600 to-blue-500 min-h-screen text-white flex items-center justify-center">
        <div className="bg-white/10 backdrop-blur-md rounded-xl p-8 shadow-lg max-w-md w-full">
          <h1 className="text-4xl font-bold mb-6 text-center text-yellow-300">Complete Your Login</h1>
          <p className="text-xl mb-4 text-center">Enter your unique username</p>
          <form className="flex flex-col items-center">
            <input
              type="text"
              name="username"
              value={username}
              onChange={handleUsernameChange}
              placeholder="ex: John123"
              className="bg-white/20 rounded-full w-full py-3 px-4 mb-4 text-white placeholder-white/70 focus:outline-none focus:ring-2 focus:ring-yellow-300"
            />
            {error && <p className="text-red-300 mb-4 text-center">{error}</p>}
            <button
              className="bg-yellow-400 hover:bg-yellow-500 text-purple-900 font-bold rounded-full py-3 px-8 transition-colors duration-200"
              onClick={handleClaim}
            >
              Claim Username
            </button>
          </form>
        </div>
      </div>
    </>
  );
}
