import { useMemo, useRef } from "react";
import { Text, View } from "react-native";
import type { Transcript } from "@/api/types";

type Sentence = Transcript["paragraphs"][number]["sentences"][number];
type Word = Transcript["words"][number];

const CHUNK_SIZE = 9;

function chunkWords(words: Word[]): Word[][] {
  const chunks: Word[][] = [];
  for (let i = 0; i < words.length; i += CHUNK_SIZE) {
    chunks.push(words.slice(i, i + CHUNK_SIZE));
  }
  return chunks;
}

interface TranscriptOverlayProps {
  transcript: Transcript;
  activeSentence: Sentence | null;
  activeWordIndex: number | null;
  /** Distance from the bottom of the parent container, in px. */
  bottomOffset: number;
}

export function TranscriptOverlay({
  transcript,
  activeSentence,
  activeWordIndex,
  bottomOffset,
}: TranscriptOverlayProps) {
  const sentenceWords = useMemo(() => {
    if (!activeSentence) return [];
    return transcript.words.filter(
      (w) => w.start >= activeSentence.start && w.end <= activeSentence.end,
    );
  }, [transcript.words, activeSentence]);

  const chunks = useMemo(() => chunkWords(sentenceWords), [sentenceWords]);

  const activeWord =
    activeWordIndex !== null ? transcript.words[activeWordIndex] : null;

  const lastSpokenWordRef = useRef<Word | null>(null);
  if (activeWord) {
    lastSpokenWordRef.current = activeWord;
  }
  const highlightWord = activeWord ?? lastSpokenWordRef.current;

  const lastChunkRef = useRef<Word[] | null>(null);

  const activeChunk = useMemo(() => {
    if (activeWord) {
      for (const chunk of chunks) {
        if (
          chunk.some(
            (w) => w.start === activeWord.start && w.end === activeWord.end,
          )
        ) {
          lastChunkRef.current = chunk;
          return chunk;
        }
      }
    }
    if (lastChunkRef.current && chunks.some((c) => c === lastChunkRef.current)) {
      return lastChunkRef.current;
    }
    const fallback = chunks[0] ?? null;
    lastChunkRef.current = fallback;
    return fallback;
  }, [chunks, activeWord]);

  if (!activeSentence || !activeChunk || activeChunk.length === 0) return null;

  return (
    <View
      pointerEvents="none"
      className="absolute left-0 right-0 items-center px-6"
      style={{ bottom: bottomOffset }}
    >
      <View className="rounded-lg px-5 py-3 max-w-[480px]">
        <Text className="text-[24px] leading-[44px] text-center">
          {activeChunk.map((word, i) => {
            const isSpoken =
              highlightWord !== null && word.start <= highlightWord.end;
            return (
              <Text
                key={`${word.start}-${i}`}
                className={
                  isSpoken ? "text-white font-medium" : "text-white/40"
                }
              >
                {i > 0 ? " " : ""}
                {word.word}
              </Text>
            );
          })}
        </Text>
      </View>
    </View>
  );
}
