import React, { useState, useRef, useEffect } from "react";

interface Props {
  text: string;
  rate?: number;
  pitch?: number;
  lang?: string;
}

const TextToSpeech: React.FC<Props> = ({
  text,
  rate = 1,
  pitch = 1,
  lang = "en-US",
}) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [currentCharIndex, setCurrentCharIndex] = useState<number | null>(null);

  const utteranceRef = useRef<SpeechSynthesisUtterance | null>(null);
  const textLength = text.length;

  useEffect(() => {
    return () => {
      window.speechSynthesis.cancel();
    };
  }, []);

  const speak = () => {
    if (!("speechSynthesis" in window)) return;

    if (isPaused) {
      window.speechSynthesis.resume();
      setIsPaused(false);
      setIsPlaying(true);
      return;
    }

    window.speechSynthesis.cancel();

    const utterance = new SpeechSynthesisUtterance(text);
    utterance.rate = rate;
    utterance.pitch = pitch;
    utterance.lang = lang;

    utterance.onboundary = (event: SpeechSynthesisEvent) => {
      if (event.name === "word") {
        setCurrentCharIndex(event.charIndex);
      }
    };

    utterance.onend = () => {
      setIsPlaying(false);
      setIsPaused(false);
      setCurrentCharIndex(null)
    };

    utterance.onerror = () => {
      setIsPlaying(false);
      setIsPaused(false);
      setCurrentCharIndex(null);
    };

    utteranceRef.current = utterance;
    window.speechSynthesis.speak(utterance);
    setIsPlaying(true);
  };


  const pause = () => {
    window.speechSynthesis.pause();
    setIsPaused(true);
    setIsPlaying(false);
  };

  const stop = () => {
    window.speechSynthesis.cancel();
    setIsPlaying(false);
    setIsPaused(false);
    setCurrentCharIndex(null);
  };

  const highlightedText = (
    <span>
      <span style={{ background: "linear-gradient(90deg, #235383, #085fb6)" }}>
        {text.substring(0, currentCharIndex ?? 0)}
      </span>
      <span>{text.substring(currentCharIndex ?? 0)}</span>
    </span>
  );

  const progressPercent =
    currentCharIndex !== null
      ? Math.min(100, Math.floor((currentCharIndex / textLength) * 100))
      : 0;

  return (
    <div style={containerStyle}>
      <div
        style={{
          fontSize: "16px",
          lineHeight: 1.5,
          marginBottom: "12px",
          userSelect: "none",
          whiteSpace: "pre-wrap",
          maxHeight: "150px",
          overflowY: "auto",
        }}
      >
        {highlightedText}
      </div>

      <div style={progressBarContainerStyle}>
        <div
          style={{
            height: "100%",
            width: `${progressPercent}%`,
            backgroundColor: "#a7afb7",
            transition: "width 0.2s ease",
          }}
        />
      </div>

      <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
        {!isPlaying ? (
          <button onClick={speak} style={buttonStyle}>
            🔊 {isPaused ? "Resume" : "Listen"}
          </button>
        ) : (
          <button onClick={pause} style={buttonStyle}>
            ⏸ Pause
          </button>
        )}

        {(isPlaying || isPaused) && (
          <button
            onClick={stop}
            style={{ ...buttonStyle, background: "#c0392b" }}
          >
            ⏹ Stop
          </button>
        )}
      </div>
    </div>
  );
};

const containerStyle: React.CSSProperties = {
  position: "fixed",
  bottom: 24,
  right: 24,
  width: 320,
  backgroundColor: "#1e2a38",
  color: "white",
  borderRadius: 16,
  boxShadow: "0 8px 24px rgba(0,0,0,0.25)",
  padding: "0px 20px",
  fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
  zIndex: 1000,
  display: "flex",
  flexDirection: "column",
};

const progressBarContainerStyle: React.CSSProperties = {
  height: 8,
  width: "100%",
  backgroundColor: "#34495e",
  borderRadius: 8,
  overflow: "hidden",
  marginBottom: 20,
  userSelect: "none",
};

const buttonStyle: React.CSSProperties = {
  flex: 1,
  padding: "10px 0",
  borderRadius: 12,
  border: "none",
  cursor: "pointer",
  fontSize: 16, 
  background:
    "linear-gradient(90deg, #235383, #085fb6)", // teal gradient
  color: "#fff",
  fontWeight: 600,
  userSelect: "none",
};

export default TextToSpeech;
