'use client';

import React, { useEffect, useState } from 'react';
import { getAuth, onAuthStateChanged, User } from 'firebase/auth';
import { useRouter } from 'next/navigation';


import { app } from '@/app/firebase/config';
import { SOLOGIN_API } from './shared';

const HomePage = () => {
  const [user, setUser] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  const auth = getAuth(app);
  const [userPubkey, setUserPubkey] = useState();

  const router = useRouter();


  const getSologinUser = async (currentUser: User)=>{
    const url = `${SOLOGIN_API}getPubkey?email=${currentUser.uid}`;
    const userDataRes = await fetch(url);
    const userDataJson = await userDataRes.json();

    return userDataJson;
  }

  const SetUser = async(currentUser:User)=>{
    const sologinUser = await getSologinUser(currentUser);
    console.log(sologinUser);
    setUser({
      name: currentUser.displayName || 'Anonymous User',
      email: currentUser.email,
      id: currentUser.uid,
      tokenId: await currentUser.getIdToken(),
      pubkey: sologinUser.pub_key
    });

  }

  const signout = async()=>{
    await auth.signOut();

  };


  useEffect(() => {

    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
      if (currentUser) {
        SetUser(currentUser);
      } else {
        router.push('/signup'); // Redirect to signup if not logged in
      }
      setLoading(false);
    });

    return () => unsubscribe(); // Cleanup subscription on unmount
  }, [auth, router]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-900 text-white">
        <p className="text-lg">Loading...</p>
      </div>
    );
  }

  if (!user) {
    return null; // Return null to avoid rendering during redirection
  }

  return (
    <div className="min-h-screen bg-gray-900 text-white flex items-center justify-center">
      <div className="bg-gray-800 p-8 rounded-lg shadow-lg w-full sm:w-96">
        <h1 className="text-3xl font-bold mb-4">Welcome</h1>
        <p className="text-lg mb-2">
          <strong>Name:</strong> {user.name}
        </p>
        <p className="text-lg mb-2">
          <strong>Email:</strong> {user.email}
        </p>
        <p className="text-lg">
          <strong>ID:</strong> {user.id}
        </p>
        <p className="text-lg">
          <strong>PubKey:</strong> {user.pubkey}
        </p>
      <button className='bg-red-500 px-5 py-2 rounded' onClick={signout}> Signout </button>

      </div>

    </div>
  );
};

export default HomePage;
