import { ref, computed } from "vue";
import Alert from "./Alert.vue";
import { createInjectionState } from "@vueuse/core";

export interface AlertState {
  visible: boolean;
  message: string;
  type: "success" | "error" | "warning" | "info";
}

// create injectivon state using vueuse
const [useAlertProvider, useAlertStore] = createInjectionState(() => {
  const alertState = ref<AlertState>({
    visible: false,
    message: "",
    type: "info",
  });

  let timeoutId: number | null = null;

  function show(
    message: string,
    type: AlertState["type"] = "info",
    duration = 2000,
  ) {
    // Clear existing timeout
    if (timeoutId) {
      window.clearTimeout(timeoutId);
    }

    alertState.value = {
      visible: true,
      message,
      type,
    };

    // Auto hide after duration
    if (duration > 0) {
      timeoutId = window.setTimeout(() => {
        hide();
      }, duration);
    }
  }

  function hide() {
    alertState.value.visible = false;
    if (timeoutId) {
      window.clearTimeout(timeoutId);
      timeoutId = null;
    }
  }

  // Convenience methods for different alert types
  function error(message: string, duration = 2000) {
    show(message, "error", duration);
  }

  function info(message: string, duration = 2000) {
    show(message, "info", duration);
  }

  function warn(message: string, duration = 2000) {
    show(message, "warning", duration);
  }

  function success(message: string, duration = 2000) {
    show(message, "success", duration);
  }

  return {
    alertState,
    show,
    hide,
    error,
    info,
    warn,
    success,
  };
});


export { Alert, useAlertProvider, useAlertStore };
