"use client";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useState } from "react";

interface TruncatedTextProps {
  text: string;
  maxWords?: number;
  className?: string;
  showMoreLabel?: string;
  fullContentTitle?: string;
}

/**
 * Displays text with truncation and a "show more" button that opens a dialog with the full content.
 * Preserves whitespace formatting like whitespace-pre-line.
 */
export function TruncatedText({
  text,
  maxWords = 50,
  className,
  showMoreLabel = "Show more",
  fullContentTitle = "Full Content",
}: TruncatedTextProps) {
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const words = text.split(/\s+/);
  const shouldTruncate = words.length > maxWords;
  const truncatedText = shouldTruncate
    ? words.slice(0, maxWords).join(" ") + "..."
    : text;

  return (
    <>
      <span className={className}>
        {truncatedText}
        {shouldTruncate && (
          <>
            {" "}
            <Button
              variant="link"
              size="xs"
              className="p-0 h-auto font-normal underline"
              onClick={() => setIsDialogOpen(true)}
            >
              {showMoreLabel}
            </Button>
          </>
        )}
      </span>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{fullContentTitle}</DialogTitle>
          </DialogHeader>
          <DialogBody>
            <p className={`text-sm text-foreground whitespace-pre-line ${className}`}>
              {text}
            </p>
          </DialogBody>
        </DialogContent>
      </Dialog>
    </>
  );
}
