import { useState } from "react";
import { useTranslation } from "react-i18n-lite";
import {
  highlightBackgroundStyle,
  markerPassageStyle,
  normalizeHighlightColor,
} from "@/constants/bookmarkHighlightColors";

const PASSAGE_COLLAPSE_CHARS = 200;
const THOUGHT_COLLAPSE_CHARS = 120;

interface CollapsibleMarkerPassageProps {
  text: string;
  highlightColor?: string | null;
  className?: string;
}

export function CollapsibleMarkerPassage({
  text,
  highlightColor,
  className = "annotation-quote marker-thread-passage",
}: CollapsibleMarkerPassageProps) {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(false);
  const collapsible = text.length > PASSAGE_COLLAPSE_CHARS;
  const color = normalizeHighlightColor(highlightColor);

  return (
    <blockquote className={className} style={markerPassageStyle(color)}>
      <span
        className={
          collapsible && !expanded
            ? "marker-passage-text marker-passage-text--clamped"
            : "marker-passage-text"
        }
        style={highlightBackgroundStyle(color)}
      >
        &ldquo;{text}&rdquo;
      </span>
      {collapsible && (
        <button
          type="button"
          className="marker-text-toggle"
          onClick={() => setExpanded((v) => !v)}
          aria-expanded={expanded}
        >
          {expanded ? t("annotations.showLess") : t("annotations.showMore")}
        </button>
      )}
    </blockquote>
  );
}

interface CollapsibleMarkerThoughtProps {
  text: string;
  className?: string;
}

export function CollapsibleMarkerThought({
  text,
  className = "marker-thread-thought",
}: CollapsibleMarkerThoughtProps) {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(false);
  const collapsible = text.length > THOUGHT_COLLAPSE_CHARS;

  return (
    <div className="marker-thought-wrap">
      <p
        className={
          collapsible && !expanded
            ? `${className} marker-thought-text marker-thought-text--clamped`
            : `${className} marker-thought-text`
        }
      >
        {text}
      </p>
      {collapsible && (
        <button
          type="button"
          className="marker-text-toggle"
          onClick={() => setExpanded((v) => !v)}
          aria-expanded={expanded}
        >
          {expanded ? t("annotations.showLess") : t("annotations.showMore")}
        </button>
      )}
    </div>
  );
}
