"use client"
import React, { createContext, useContext } from "react"
import toast, { Toaster, ToastBar } from "react-hot-toast"

interface ToasterContextProps {
  showSuccess: (message: string) => void
  showError: (message: string) => void
  showInfo: (message: string) => void
}

const ToasterContext = createContext<ToasterContextProps | undefined>(undefined)

export function ToasterProvider({ children }: { children: React.ReactNode }) {
  // Only run toast on client
  const showSuccess = (message: string) => {
    if (typeof window !== "undefined") {
      toast.success(message, {
        style: {
          background: "linear-gradient(90deg, #2b6cb0 0%, #3182ce 100%)",
          color: "#fff",
          borderRadius: "0.75rem",
          fontWeight: 600,
          fontFamily: "Inter, sans-serif",
          boxShadow: "0 4px 24px rgba(44, 62, 80, 0.12)"
        },
        iconTheme: {
          primary: "#3182ce",
          secondary: "#fff"
        }
      })
    }
  }

  const showError = (message: string) => {
    if (typeof window !== "undefined") {
      toast.error(message, {
        style: {
          background: "linear-gradient(90deg, #e53e3e 0%, #f56565 100%)",
          color: "#fff",
          borderRadius: "0.75rem",
          fontWeight: 600,
          fontFamily: "Inter, sans-serif",
          boxShadow: "0 4px 24px rgba(44, 62, 80, 0.12)"
        },
        iconTheme: {
          primary: "#e53e3e",
          secondary: "#fff"
        }
      })
    }
  }

  const showInfo = (message: string) => {
    if (typeof window !== "undefined") {
      toast(message, {
        style: {
          background: "linear-gradient(90deg, #64748b 0%, #94a3b8 100%)",
          color: "#fff",
          borderRadius: "0.75rem",
          fontWeight: 600,
          fontFamily: "Inter, sans-serif",
          boxShadow: "0 4px 24px rgba(44, 62, 80, 0.12)"
        },
        iconTheme: {
          primary: "#64748b",
          secondary: "#fff"
        }
      })
    }
  }

  return (
    <ToasterContext.Provider value={{ showSuccess, showError, showInfo }}>
      {children}
      <Toaster position="top-right" toastOptions={{ duration: 4000 }}>
        {t => <ToastBar toast={t} />}
      </Toaster>
    </ToasterContext.Provider>
  )
}

export function useToaster() {
  const context = useContext(ToasterContext)
  if (!context) {
    throw new Error("useToaster must be used within a ToasterProvider")
  }
  return context
}
