import React, { useEffect, useRef, useState } from "react"
import { eventBus } from "../utils/eventBus"

interface LoaderProps {
  text: string
  icon?: React.ReactNode
  listeningTo?: string
  initialBuffer?: string
  minheight?: string
}

const Loader: React.FC<LoaderProps> = ({
  text,
  icon,
  listeningTo,
  initialBuffer,
  minheight = "min-h-screen",
}) => {
  const [buffer, setBuffer] = useState(initialBuffer || "")
  const preRef = useRef<HTMLPreElement>(null)

  useEffect(() => {
    if (listeningTo) {
      eventBus.on(listeningTo, (e: any) => {
        setBuffer((prev) => prev + "\n" + e.message)
      })
    }
    return () => {
      if (listeningTo) {
        eventBus.off(listeningTo)
      }
    }
  }, [listeningTo])

  useEffect(() => {
    if (preRef.current) {
      preRef.current.scrollTo({
        top: preRef.current.scrollHeight,
        behavior: "smooth",
      })
    }
  }, [buffer])

  return (
    <div
      className={`flex flex-col items-center justify-center  bg-gray-50 text-center space-y-6 ${minheight}`}
    >
      <div className="text-blue-500 text-4xl animate-pulse">{icon}</div>
      <p className="text-gray-800 text-lg whitespace-pre-line px-4">{text}</p>
      {!buffer && (
        <div className="flex space-x-2 mt-2">
          {[0, 1, 2, 3].map((i) => (
            <span
              key={i}
              className="w-2 h-2 rounded-full bg-blue-400 opacity-30 animate-ping"
              style={{
                animationDelay: `${i * 0.2}s`,
                animationDuration: "1.2s",
              }}
            />
          ))}
        </div>
      )}
      {buffer && (
        <pre
          ref={preRef}
          className="text-gray-800 text-sm  border border-blue-200  rounded-md p-3 font-sans max-h-[300px] overflow-y-auto w-full max-w-[700px] text-left"
          style={{ scrollbarWidth: "none" }}
        >
          {buffer.trim()}
        </pre>
      )}
    </div>
  )
}

export default Loader
