'use client';

import { useMemo } from 'react';
import { FileText } from 'lucide-react';

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';

import { MarkdownMessage } from '../../dev/code/MarkdownMessage';

export interface PastedTextDialogProps {
  /** Whether the dialog is open. */
  open: boolean;
  /** Open-state change handler (Esc / overlay click / close button). */
  onOpenChange: (open: boolean) => void;
  /** The raw pasted text to preview. */
  text: string;
  /** Short title shown in the header (the chip's derived title). */
  title?: string;
}

/**
 * Read-only preview for a "Pasted text" attachment chunk.
 *
 * Renders the raw paste through `MarkdownMessage` — the same chat-tuned
 * renderer used for message bubbles, so fenced code blocks, tables and
 * GFM all come out formatted, with the plain-text fast path kicking in
 * for prose-only pastes. View-only by design: there is no edit affordance.
 *
 * Built on ui-core's radix `Dialog` primitive with local open-state — it
 * does not touch the global `dialog-service` (that service is shaped for
 * imperative string-message alerts/confirms, not arbitrary content). The
 * caller owns `open` so the chip can drive it from a click.
 */
export function PastedTextDialog({
  open,
  onOpenChange,
  text,
  title,
}: PastedTextDialogProps) {
  // A rough size hint for the header (chars / KB) — cheap, derived.
  const meta = useMemo(() => {
    const chars = text.length;
    const kb = new Blob([text]).size / 1024;
    return kb >= 1
      ? `${chars.toLocaleString()} chars · ${kb.toFixed(1)} KB`
      : `${chars.toLocaleString()} chars`;
  }, [text]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className={cn(
          'flex max-h-[80dvh] w-full max-w-2xl flex-col gap-3 p-0',
        )}
        // This is a read-only preview — there is no primary action to
        // focus. radix would otherwise autofocus the first focusable node,
        // which is the (visually hover-hidden) "Copy" button inside the
        // markdown code block — surfacing a stray focus ring on open.
        // Prevent the default and keep focus on the panel itself; Esc /
        // overlay click still dismiss, and Tab reaches controls normally.
        onOpenAutoFocus={(e) => e.preventDefault()}
      >
        <DialogHeader className="shrink-0 space-y-1 border-b border-border px-5 pb-3 pt-5 text-left">
          <DialogTitle className="flex items-center gap-2 text-base">
            <span className="grid size-7 shrink-0 place-items-center rounded-md bg-primary/15 text-primary">
              <FileText aria-hidden className="size-4" />
            </span>
            <span className="min-w-0 truncate">{title ?? 'Pasted text'}</span>
          </DialogTitle>
          <p className="pl-9 text-xs text-muted-foreground">{meta}</p>
        </DialogHeader>

        {/* Scrollable body — `MarkdownMessage` formats the paste. */}
        <div className="min-h-0 flex-1 overflow-y-auto px-5 pb-5">
          <MarkdownMessage content={text} size="sm" />
        </div>
      </DialogContent>
    </Dialog>
  );
}

export default PastedTextDialog;
