import { createClient } from "@/utils/supabase/client";
import { Auth } from "@supabase/auth-ui-react";
import { ThemeSupa } from "@supabase/auth-ui-shared";
import { AuthChangeEvent } from "@supabase/supabase-js";
import { Modal } from "antd";
import { atom, useAtom, useSetAtom } from "jotai";
import { useEffect } from "react";

export const authModalAtom = atom(false);
export const authStateAtom = atom<AuthChangeEvent>("INITIAL_SESSION");

const supabase = createClient();

const AuthModal = () => {
  const [modalOpen, setModalOpen] = useAtom(authModalAtom);
  const setAuthState = useSetAtom(authStateAtom);

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      if (data?.session) {
        supabase.auth.setSession(data.session);
      }
    });

    const { data: authListener } = supabase.auth.onAuthStateChange(
      (event, session) => {
        setAuthState(event);
        
        if (event === "SIGNED_IN") {
          setModalOpen(false);
        }
      }
    );

    return () => {
      authListener?.subscription?.unsubscribe();
    };
  }, []);

  return (
    <Modal open={modalOpen} onCancel={() => setModalOpen(false)} footer={null}>
      <Auth
        supabaseClient={supabase}
        appearance={{
          theme: ThemeSupa,
          variables: {
            default: {
              colors: {
                brand: "#1677ff",
                brandAccent: "#4096ff",
              },
            },
          },
        }}
        providers={[]}
      />
    </Modal>
  );
};

export default AuthModal;
