"use client";

import { signIn, signOut } from "next-auth/react";
import { SyntheticEvent, useState } from "react";
import { Session } from "next-auth";
import { Button } from "@nextui-org/button";
import { Spinner } from "@nextui-org/react";

interface SignInProps {
  session: Session | null;
}

export default function SignIn({ session }: SignInProps) {
  const [loading, setLoading] = useState(false);
  const handleSignIn = async (event: SyntheticEvent) => {
    event.preventDefault();
    setLoading(true);
    await signIn("github");
  };

  const handleSignOut = async (event: SyntheticEvent) => {
    event.preventDefault();
    setLoading(true);
    await signOut();
  };

  return (
    <>
      {session?.user ? (
        <form onSubmit={handleSignOut}>
          <Button type="submit" disabled={loading}>
            Sign out
          </Button>
        </form>
      ) : (
        <form onSubmit={handleSignIn}>
          {!loading ? (
            <Button type="submit" disabled={loading}>
              Sign in
            </Button>
          ) : (
            <Spinner color="success" />
          )}
        </form>
      )}
    </>
  );
}
