"use client";

import { memo } from "react";
import type { TextBlockProps } from "./TextBlock.types";

type TextRow = NonNullable<TextBlockProps["rows"]>[number];

/**
 * Figma: Utility / **Community Rule / Text Block** (22001:29793).
 * Title + body paragraphs and/or labeled rows (12px between stacks, 8px label→body).
 */

const ENTRY_TITLE_CLASS =
  "text-x-small-heading text-[var(--color-content-invert-primary)] shrink-0";

const ROW_LABEL_CLASS =
  "font-medium text-[14px] leading-[18px] text-[var(--color-content-invert-primary)] shrink-0";

const PARAGRAPH_CLASS =
  "text-small-paragraph text-[var(--color-content-invert-primary)] shrink-0";

function bodyToParagraphs(body: string): string[] {
  return body
    .split(/\n\n/)
    .map((s) => s.trim())
    .filter((s) => s.length > 0);
}

function ParagraphGroup({ text }: { text: string }) {
  const paragraphs = bodyToParagraphs(text);
  if (paragraphs.length === 0) return null;
  return (
    <div className="flex min-w-0 flex-col gap-2">
      {paragraphs.map((p, i) => (
        <p key={i} className={`${PARAGRAPH_CLASS} whitespace-pre-wrap`}>
          {p}
        </p>
      ))}
    </div>
  );
}

function LabeledRowView({ row }: { row: TextRow }) {
  const imageSrc = row.imageUrl?.trim();
  const fileHref = row.fileUrl?.trim();
  const caption = row.body.trim();
  const hasCaption = caption.length > 0;
  const alt = hasCaption ? caption : row.label;
  const linkText = hasCaption ? caption : fileHref;

  return (
    <div className="flex min-w-0 flex-col gap-2">
      <p className={ROW_LABEL_CLASS}>{row.label}</p>
      {imageSrc ? (
        <>
          {/* eslint-disable-next-line @next/next/no-img-element -- same-origin or absolute upload URL */}
          <img
            src={imageSrc}
            alt={alt}
            className="max-h-[240px] max-w-full rounded-[var(--measures-radius-200,8px)] object-contain"
          />
          {hasCaption ? <ParagraphGroup text={row.body} /> : null}
        </>
      ) : fileHref ? (
        <p className={`${PARAGRAPH_CLASS} whitespace-pre-wrap`}>
          <a
            href={fileHref}
            className="underline"
            target="_blank"
            rel="noopener noreferrer"
          >
            {linkText}
          </a>
        </p>
      ) : (
        <ParagraphGroup text={row.body} />
      )}
    </div>
  );
}

function TextBlockView({
  title,
  body = "",
  rows,
  className = "",
}: TextBlockProps) {
  const hasRows = rows && rows.length > 0;

  return (
    <div
      className={`flex min-w-0 flex-col gap-2 ${className}`.trim()}
      data-name="TextBlock"
    >
      <p className={`${ENTRY_TITLE_CLASS} w-full min-w-0`}>{title}</p>
      <div className="flex min-w-0 flex-col gap-3">
        {body.trim().length > 0 ? <ParagraphGroup text={body} /> : null}
        {hasRows
          ? rows!.map((row, i) => <LabeledRowView key={i} row={row} />)
          : null}
      </div>
    </div>
  );
}

TextBlockView.displayName = "TextBlockView";

export default memo(TextBlockView);
