'use client'

import Image from 'next/image'
import { useEffect, useState } from 'react'
import {account, ID} from './appwrite'

export default function Home() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [user, setUser] = useState(null);
  const [loadingUser, setLoadingUser] = useState(true)

console.log({user})

  useEffect(() => {
    async function getUser(){
      setUser(await account.get())
      setLoadingUser(false)
    }
    getUser();
  }, [])

  async function handleLogout(){
    try {
      await account.deleteSession('current');
      setUser(null)    
    } catch (e){
      console.error(e)
    }
  }


  async function handleLogin(){
    try {
      await account.createEmailSession(email, password);
      setUser(await account.get())
      setEmail('')
      setPassword('')      
    } catch (e){
      console.error(e)
    }
  }

  async function handleRegister(){
    try {
      await account.create(ID.unique(), email, password)
      await handleLogin()
    } catch (e){
      console.error(e)
    }
  }

  if (loadingUser) {

    return (
      <div className="bg-gray-800 p-8 max-w-sm mx-auto rounded-lg shadow-md mt-10">
        <div className="flex items-center">
          <svg className="h-6 w-6 text-blue-500 mr-4" fill="none" strokeLinecap="round">
            <path d="M5 13l4 4L19 7"></path>
          </svg>
          <p className="text-white font-semibold text-lg"> Loading User</p>
        </div>
      </div>
    )

  }

  if (user) {
    return (
      <div className="bg-gray-800 p-8 max-w-sm mx-auto rounded-lg shadow-md mt-10">
        <div className="flex items-center">
          <svg className="h-6 w-6 text-blue-500 mr-4" fill="none" strokeLinecap="round">
            <path d="M5 13l4 4L19 7"></path>
          </svg>
          <p className="text-white font-semibold text-lg"> You're already logged in</p>
          <button 
            type="button"
            onClick={handleLogout}>
            Logout
        </button>
        </div>
      </div>
    )
  }


  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <h1>Login or Sign Up Page</h1>

      <form>

        <input 
        type="email" 
        placeholder='Email' 
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        />

        <input 
        type="password" 
        placeholder='Password' 
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        />
        
        <button 
        type="button"
        onClick={handleLogin}>
          Login
        </button>

        <button 
        type="button"
        onClick={handleRegister}>
          Register
        </button>

      </form>
    </main>
  )
}
