import React, { createContext, useState, ReactNode } from 'react';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/use-toast';
import { AuthModal } from '@/components/auth/AuthModal';

interface AuthModalContextType {
  openAuthModal: (defaultTab?: 'signin' | 'signup') => void;
  requireAuth: (callback: () => void, message?: string) => void;
  authModalOpen: boolean;
  setAuthModalOpen: (open: boolean) => void;
}

export const AuthModalContext = createContext<AuthModalContextType | undefined>(undefined);

interface AuthModalProviderProps {
  children: ReactNode;
}

export function AuthModalProvider({ children }: AuthModalProviderProps) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [authModalOpen, setAuthModalOpen] = useState(false);
  const [authModalTab, setAuthModalTab] = useState<'signin' | 'signup'>('signin');

  const openAuthModal = (defaultTab: 'signin' | 'signup' = 'signin') => {
    setAuthModalTab(defaultTab);
    setAuthModalOpen(true);
  };

  const requireAuth = (callback: () => void, message?: string) => {
    if (user) {
      callback();
    } else {
      toast({
        title: "Authentication Required",
        description: message || "Please sign in to continue",
      });
      openAuthModal('signin');
    }
  };

  return (
    <AuthModalContext.Provider
      value={{
        openAuthModal,
        requireAuth,
        authModalOpen,
        setAuthModalOpen,
      }}
    >
      {children}
      <AuthModal 
        open={authModalOpen} 
        onOpenChange={setAuthModalOpen}
        defaultTab={authModalTab}
      />
    </AuthModalContext.Provider>
  );
}
