import React, { createContext, useContext, useState, useCallback } from 'react';

type AuthModalType = 'login' | 'register' | 'forgot-password' | 'reset-password' | null;
type ResetPasswordParams = { token: string } | null;

interface AuthModalContextType {
  isOpen: boolean;
  modalType: AuthModalType;
  resetPasswordParams: ResetPasswordParams;
  openModal: (type: AuthModalType, params?: ResetPasswordParams) => void;
  closeModal: () => void;
}

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

export const AuthModalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [modalType, setModalType] = useState<AuthModalType>(null);
  const [resetPasswordParams, setResetPasswordParams] = useState<ResetPasswordParams>(null);

  const openModal = useCallback((type: AuthModalType, params?: ResetPasswordParams) => {
    setModalType(type);
    setResetPasswordParams(params || null);
    setIsOpen(true);
    document.body.style.overflow = 'hidden';
  }, []);

  const closeModal = useCallback(() => {
    setIsOpen(false);
    setModalType(null);
    setResetPasswordParams(null);
    document.body.style.overflow = 'unset';
  }, []);

  return (
    <AuthModalContext.Provider
      value={{
        isOpen,
        modalType,
        resetPasswordParams,
        openModal,
        closeModal,
      }}
    >
      {children}
    </AuthModalContext.Provider>
  );
};

// eslint-disable-next-line react-refresh/only-export-components
export const useAuthModal = () => {
  const context = useContext(AuthModalContext);
  if (context === undefined) {
    throw new Error('useAuthModal must be used within an AuthModalProvider');
  }
  return context;
};

