import React, { useMemo, useState } from "react";
import { Box, Text, UseInput } from "./Ink";

type ScrollableTextProps = {
  width: number;
  height: number;
  text: string;
  useInput: UseInput;
};

export const ScrollableText = ({
  width,
  height,
  text,
  useInput,
}: ScrollableTextProps) => {
  const [scroll, setScroll] = useState(0);

  const lines = useMemo(() => text.split("\n"), [text]);

  const displayedLines = lines.slice(scroll, scroll + height);

  useInput((input, key) => {
    if (key.upArrow) {
      setScroll(Math.max(scroll - 1, 0));
    } else if (key.downArrow) {
      setScroll(Math.min(scroll + 1, lines.length - height));
    }
  });

  return (
    <Box flexDirection="column" width={width} height={height}>
      {displayedLines.map((line, index) => (
        <Text key={index + scroll}>{line}</Text>
      ))}
    </Box>
  );
};
