"use client";

import { useTranslation } from "react-i18next";
import CaptionWithMentions from "@/components/posts/CaptionWithMentions";
import {
  getCollapsedCaptionPreview,
  postCaptionNeedsMore,
} from "@/lib/postLinkCaption";
import { cn } from "@/lib/utils";

type ExpandableCaptionProps = {
  body: string;
  links?: string;
  expanded: boolean;
  onToggle: () => void;
  variant?: "post" | "reels";
  className?: string;
  mentionClassName?: string;
  hashtagClassName?: string;
  linkClassName?: string;
  moreClassName?: string;
  scrollWhenExpanded?: boolean;
};

function splitLinkLines(links: string): string[] {
  return links
    .split("\n")
    .flatMap((line) => line.split(/\s+–\s+/))
    .map((line) => line.trim())
    .filter(Boolean);
}

export default function ExpandableCaption({
  body,
  links = "",
  expanded,
  onToggle,
  variant = "post",
  className,
  mentionClassName,
  hashtagClassName,
  linkClassName,
  moreClassName,
  scrollWhenExpanded = false,
}: ExpandableCaptionProps) {
  const { t } = useTranslation("common");
  const needsMore = postCaptionNeedsMore(body);
  const displayBody =
    expanded || !needsMore ? body : getCollapsedCaptionPreview(body);
  const linkLines = splitLinkLines(links);
  const showLinks =
    linkLines.length > 0 && (expanded || !needsMore);

  const isReels = variant === "reels";
  const resolvedMention =
    mentionClassName ??
    (isReels
      ? "font-bold text-white hover:underline"
      : "font-bold text-blue-400 hover:underline");
  const resolvedHashtag =
    hashtagClassName ??
    (isReels ? "font-bold text-blue-300" : "font-bold text-blue-500");
  const resolvedLink =
    linkClassName ??
    (isReels
      ? "font-bold text-[#FF107D] hover:underline"
      : "font-bold text-[#FF107D] hover:underline");
  const resolvedMore =
    moreClassName ??
    (isReels
      ? "text-xs font-semibold text-white/75"
      : "text-sm font-bold text-neutral-500");

  if (!body.trim() && !showLinks) return null;

  const content = (
    <>
      {body.trim() ? (
        <div
          className={cn(
            "text-sm font-medium leading-6",
            isReels ? "text-white/95" : "text-justify",
            className
          )}
        >
          <div
            className={cn(
              !expanded && needsMore && "line-clamp-1 whitespace-pre-wrap"
            )}
          >
            <CaptionWithMentions
              text={displayBody}
              mentionClassName={resolvedMention}
              hashtagClassName={resolvedHashtag}
              linkClassName={resolvedLink}
            />
          </div>
          {needsMore ? (
            <>
              {" "}
              <button
                type="button"
                className={cn(
                  "inline cursor-pointer align-baseline whitespace-nowrap",
                  resolvedMore
                )}
                onClick={(e) => {
                  e.stopPropagation();
                  onToggle();
                }}
              >
                {expanded ? t("posts.less") : t("posts.more")}
              </button>
            </>
          ) : null}
        </div>
      ) : null}
      {showLinks
        ? linkLines.map((line, index) => (
            <p
              key={`${line}-${index}`}
              className={cn(
                "text-sm font-medium leading-6 whitespace-pre-wrap",
                index === 0 ? "mt-1" : "mt-0.5",
                isReels ? "text-white/95" : "text-justify",
                className
              )}
            >
              <CaptionWithMentions
                text={line}
                mentionClassName={resolvedMention}
                hashtagClassName={resolvedHashtag}
                linkClassName={resolvedLink}
              />
            </p>
          ))
        : null}
    </>
  );

  if (scrollWhenExpanded && expanded && needsMore) {
    return (
      <div
        className="max-h-[min(45dvh,320px)] touch-pan-y overflow-y-auto overscroll-y-contain [-webkit-overflow-scrolling:touch]"
        onPointerDown={(e) => e.stopPropagation()}
        onTouchStart={(e) => e.stopPropagation()}
      >
        {content}
      </div>
    );
  }

  return content;
}
