
'use client';

import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react';

type LoadingState = {
  isLoading: boolean;
  title?: string;
  description?: string;
};

type LoadingContextType = {
  loadingState: LoadingState;
  show: (options?: { title?: string; description?: string }) => void;
  hide: () => void;
};

const LoadingContext = createContext<LoadingContextType | undefined>(undefined);

export const LoadingProvider = ({ children }: { children: ReactNode }) => {
  const [loadingState, setLoadingState] = useState<LoadingState>({
    isLoading: false,
    title: 'Loading...',
    description: 'Please wait while we process your request.',
  });

  const show = useCallback((options?: { title?: string; description?: string }) => {
    setLoadingState({
      isLoading: true,
      title: options?.title || 'Loading Workspace',
      description: options?.description || 'Connecting to secure database...',
    });
  }, []);

  const hide = useCallback(() => {
    setLoadingState(prevState => ({ ...prevState, isLoading: false }));
  }, []);

  return (
    <LoadingContext.Provider value={{ loadingState, show, hide }}>
      {children}
    </LoadingContext.Provider>
  );
};

export const useLoading = (): {
  show: (options?: { title?: string; description?: string }) => void;
  hide: () => void;
} => {
  const context = useContext(LoadingContext);
  if (context === undefined) {
    throw new Error('useLoading must be used within a LoadingProvider');
  }
  const { show, hide } = context;
  return { show, hide };
};

export const useLoadingState = (): LoadingState => {
    const context = useContext(LoadingContext);
    if (context === undefined) {
        throw new Error('useLoadingState must be used within a LoadingProvider');
    }
    return context.loadingState;
}
