import {usePrivy} from '@privy-io/react-auth'
import {useAccount} from 'wagmi'

import LogIn from '../../components/mollecules/LogIn/LogIn'
import useCookie from '../../hooks/useCookie'
import {useEffect, useState} from 'react'
import {useAuthStore} from '../../app/store/accountStore'

export const Auth = ({ children }: any) => {
  const { getCookie, deleteCookie } = useCookie()
  const { isConnected } = useAccount()
  const { login, ready, authenticated, user } = usePrivy()
  const token = getCookie('token')
  const onInitialize = useAuthStore((state) => state.onInitialize)
  
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (ready) {
      const timeout = setTimeout(() => {
        setIsLoading(false);
      }, 1000);
      
      return () => clearTimeout(timeout);
    }
  }, [ready]);

  // Initialize accounts when authenticated and token is available
  useEffect(() => {
    if (authenticated && token) {
      onInitialize()
    }
  }, [authenticated, token, onInitialize]);

  if (!ready || isLoading) {
    return <div>Loading...</div>;
  }

  if (!authenticated) {
    deleteCookie('token')
    return (
      <div style={{ ...styles }}>
        <button 
          onClick={login}
          style={{
            padding: '10px 20px',
            backgroundColor: '#3B82F6',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '16px'
          }}
        >
          Login with Privy
        </button>
      </div>
    )
  } else if (!token) {
    return <LogIn />
  } else {
    return children
  }
}

const styles = {
  alignItems: 'center',
  display: 'flex',
  height: '100vh',
  justifyContent: 'center',
}
