import React, { createContext, useState, useContext, useRef } from 'react';
import { useErrorStore } from 'src/stores/errorStore';

const ErrorContext = createContext<{
  error: string | null;
  showError: (message: string, loginNeeded: boolean) => void;
  hideError: () => void;
  resetErrorState: () => void;
  navigateToLogin: boolean;
  navigateToAuth: boolean;
  premiumError: boolean;
}>({
  error: null,
  showError: (message: string, loginNeeded: boolean) => {},
  hideError: () => {},
  resetErrorState: () => {},
  navigateToLogin: false,
  navigateToAuth: false,
  premiumError: false
});

export const ErrorProvider = ({ children }: { children: React.ReactNode }) => {
  const { isErrorShown, setErrorShown } = useErrorStore.getState();
  const [error, setError] = useState<string | null>(null);
  const [navigateToLogin, setNavigateToLogin] = useState<boolean>(false);
  const [navigateToAuth, setNavigateToAuth] = useState<boolean>(false);
  const [premiumError, setPremiumError] = useState<boolean>(false);

  const showError = (
    message: string,
    loginNeeded: boolean,
    authNeeded: boolean = false,
    premiumNeeded: boolean = false
  ) => {
    if (!isErrorShown) {
      setErrorShown(true);
      setError(message);
      setNavigateToLogin(loginNeeded);
      setNavigateToAuth(authNeeded);
      setPremiumError(premiumNeeded);
    }
  };

  const hideError = () => {
    setError(null);
  };

  const resetErrorState = () => {
    setTimeout(() => {
      setErrorShown(false);
    }, 10000);
  };

  return (
    <ErrorContext.Provider
      value={{
        error,
        showError,
        hideError,
        resetErrorState,
        navigateToLogin,
        navigateToAuth,
        premiumError
      }}
    >
      {children}
    </ErrorContext.Provider>
  );
};

export const useError = () => useContext(ErrorContext);
