import { useState } from "react"
import useLocalStorage from "use-local-storage"
import { useAtom } from "jotai"
import { loginStatusAtom } from "../state/atoms"
import { LoginHelper } from "../lib/session"

export const LoginWidget = () => {
  const [username, setUsername] = useLocalStorage("input_username","", {syncData: false})
  const [password, setPassword] = useState("")

  const [{data:loginState, refetch: refetchLoginState}] = useAtom(loginStatusAtom)

  const [loginError, setLoginError] = useState("")

  if(loginState?.logged_in){
    return <>
      <div className="flex flex-row justify-between px-2">
        <div>
          {loginState.community_name}
        </div>
        <div className="flex flex-row gap-2">
          <button
            onClick={()=>{
              LoginHelper.logout().finally(()=>{
                refetchLoginState()
              })
              return
            }}
            className="text-blue-400 text-xs hover:cursor-pointer hover:text-blue-600">
            logout
          </button>
        </div>
      </div>

    </>
  }

  return <>
    <div className="flex flex-col">
      <form action={
        ()=>{
          LoginHelper.login(username,password).catch((e)=>{
            setLoginError(e.message)
          }).finally(()=>{
              refetchLoginState()
              refetchLoginState()
            })
        }}
        className="flex flex-col gap-1 p-2 justify-left">
        { loginError ? (<div className="text-red-500 text-xs">
          {loginError}
        </div>) : null}
        <div>
          <input
            onChange={(e)=>{
              setUsername(e.target.value)
            }}
            value={username}
            id="username"
            placeholder="username" className="w-32 pl-2 pb-1 border-b border-gray-600 placeholder-gray-500"/>
        </div>
        <div>
          <input
            onChange={(e)=>{
              setPassword(e.target.value)
            }}
            value={password}
            type="password" placeholder="password" className="w-32 pl-2 pb-1 border-b border-gray-600 placeholder-gray-500"/>
        </div>
        <button
          type="submit"
          className="border-b border-gray-600 px-2 py-1 hover:text-gray-600 hover:cursor-pointer">
          login
        </button>
      </form>
    </div>
  </>
}


