import { useState, useCallback } from 'react';
import { useToast, UseToastOptions } from '@chakra-ui/react';

interface UseAdminPageOptions {
  successMessage?: string;
  errorMessage?: string;
  toastPosition?: UseToastOptions['position'];
}

export const useAdminPage = (options: UseAdminPageOptions = {}) => {
  const {
    successMessage = 'Operation completed successfully',
    errorMessage = 'An error occurred',
    toastPosition = 'top-right',
  } = options;

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const toast = useToast();

  const handleAsyncOperation = useCallback(
    async <T,>(
      operation: () => Promise<T>,
      customMessages?: {
        success?: string;
        error?: string;
      }
    ): Promise<T | undefined> => {
      setIsLoading(true);
      setError(null);

      try {
        const result = await operation();
        
        toast({
          title: 'Success',
          description: customMessages?.success || successMessage,
          status: 'success',
          duration: 3000,
          isClosable: true,
          position: toastPosition,
        });
        
        return result;
      } catch (err) {
        const error = err instanceof Error ? err : new Error(errorMessage);
        setError(error);
        
        toast({
          title: 'Error',
          description: customMessages?.error || error.message || errorMessage,
          status: 'error',
          duration: 5000,
          isClosable: true,
          position: toastPosition,
        });
        
        return undefined;
      } finally {
        setIsLoading(false);
      }
    },
    [successMessage, errorMessage, toast, toastPosition]
  );

  const resetError = useCallback(() => {
    setError(null);
  }, []);

  return {
    isLoading,
    error,
    handleAsyncOperation,
    resetError,
  };
};
