import React, { createContext, useContext, useState, ReactNode } from "react";
import { Toast, Frame } from "@shopify/polaris";

interface ToastOptions {
  message: string;
  error?: boolean;
  duration?: number;
  action?: {
    content: string;
    onAction: () => void;
  };
}

interface ToastContextType {
  showToast: (options: ToastOptions) => void;
  showSuccess: (message: string) => void;
  showError: (message: string) => void;
}

const ToastContext = createContext<ToastContextType | undefined>(undefined);

export function ToastProvider({ children }: { children: ReactNode }) {
  const [toast, setToast] = useState<ToastOptions | null>(null);

  const showToast = (options: ToastOptions) => {
    setToast(options);
  };

  const showSuccess = (message: string) => {
    setToast({ message, error: false });
  };

  const showError = (message: string) => {
    setToast({ message, error: true });
  };

  const dismissToast = () => {
    setToast(null);
  };

  const toastMarkup = toast ? (
    <Toast
      content={toast.message}
      error={toast.error}
      duration={toast.duration}
      action={toast.action}
      onDismiss={dismissToast}
    />
  ) : null;

  return (
    <ToastContext.Provider value={{ showToast, showSuccess, showError }}>
      <Frame>
        {children}
        {toastMarkup}
      </Frame>
    </ToastContext.Provider>
  );
}

export function useToast() {
  const context = useContext(ToastContext);
  if (context === undefined) {
    throw new Error("useToast must be used within a ToastProvider");
  }
  return context;
}
