'use client'

import { serverAttemptAuthenticateUser } from "@/app/lib/actions/actions";
import { AuthContext } from "@/providers/providers";
import { constructAPIUrl } from "@/util/url";
import { createContext, useState } from "react";
import { useFormState, useFormStatus } from "react-dom";


// async function authenticate(){
//     const url = await constructAPIUrl("auth");
//     const auth = await fetch(url);
// }


export default function LoginForm(){
    const [loginResult, dispatch] = useFormState(serverAttemptAuthenticateUser, undefined);

    return (
    <form className="bg-background-400 border-4 border-primary-500 drop-shadow-md w-fit p-3 rounded-lg flex flex-col gap-1" action={dispatch}>
        <label htmlFor="input_username">Username</label>
        <input type="text" name="input_username" id="input_username" className="bg-secondary border-2 border-primary rounded-lg drop-shadow-md" />
        <label htmlFor="input_password">Password</label>
        <input type="password" name="input_password" id="input_password" className="bg-secondary outline-primary border-2 border-primary rounded-lg drop-shadow-md shadow-inner shadow-primary" />
        <LoginButton></LoginButton>
        <div>{loginResult?.errorMessage && <p>{loginResult?.errorMessage}</p>}</div>
        <div className="flex flex-col w-[400px] break-words ">
            <p>{""+loginResult?.cookie}</p>
        </div>
    </form>);
}

function LoginButton() {
    const { pending } = useFormStatus()
   
    return (
      <button aria-disabled={pending} className="mr-auto bg-secondary-200 outline outline-2 border-5 p-3 mt-3 rounded-lg outline-secondary-500  shadow-primary" type="submit">
        {!pending ? 'Sign In' : 'Pending Sign In...'}
      </button>
    )
  }