import { useEffect, type ReactNode } from "react";
import { ArrowBigLeft, ArrowBigLeftDash, ArrowBigRight, ArrowBigRightDash } from "lucide-react";
import { Button, MessageDisplayPanel, type MessageDisplayAttachment } from "@govoplan/core-webui";

// Campaign review/template/mock previews need recipient navigation, review notes,
// raw MIME inspection and attachment grouping. Generic mailbox reading uses
// core MessageDisplayPanel instead.
export type CampaignMessagePreviewAttachment = MessageDisplayAttachment & {
  label?: string | null;
};

export type CampaignMessagePreviewMetaItem = {
  label: string;
  value: ReactNode;
};

export type CampaignMessagePreviewNavigation = {
  index: number;
  total: number;
  onFirst: () => void;
  onPrevious: () => void;
  onNext: () => void;
  onLast: () => void;
};

export type CampaignMessagePreviewOverlayProps = {
  title?: string;
  subject?: string | null;
  bodyMode?: "text" | "html";
  text?: string | null;
  html?: string | null;
  recipientLabel?: ReactNode;
  recipientNote?: ReactNode;
  metaItems?: CampaignMessagePreviewMetaItem[];
  attachments?: CampaignMessagePreviewAttachment[];
  raw?: string | null;
  rawLabel?: string;
  navigation?: CampaignMessagePreviewNavigation;
  closeLabel?: string;
  onClose: () => void;
};

export default function CampaignMessagePreviewOverlay({
  title = "Message preview",
  subject,
  bodyMode = "text",
  text,
  html,
  recipientLabel,
  recipientNote,
  metaItems = [],
  attachments = [],
  raw,
  rawLabel = "Raw MIME",
  navigation,
  closeLabel = "Close",
  onClose
}: CampaignMessagePreviewOverlayProps) {
  const shownSubject = subject?.trim() || "No subject";
  const fields = metaItems.map((item) => ({ label: item.label, value: item.value }));

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (isEditableTarget(event.target)) return;
      if (event.key === "Escape") {
        event.preventDefault();
        onClose();
        return;
      }
      if (!navigation) return;
      if (event.key === "ArrowLeft") {
        event.preventDefault();
        if (navigation.index > 0) navigation.onPrevious();
      } else if (event.key === "ArrowRight") {
        event.preventDefault();
        if (navigation.index < navigation.total - 1) navigation.onNext();
      } else if (event.key === "Home") {
        event.preventDefault();
        if (navigation.index > 0) navigation.onFirst();
      } else if (event.key === "End") {
        event.preventDefault();
        if (navigation.index < navigation.total - 1) navigation.onLast();
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [navigation, onClose]);

  return (
    <div className="overlay-backdrop" role="dialog" aria-modal="true" aria-labelledby="message-preview-title">
      <div className="modal-panel template-preview-modal message-preview-modal">
        <header className="modal-header">
          <h2 id="message-preview-title">{title}</h2>
          <button className="modal-close" onClick={onClose}>×</button>
        </header>
        <div className="modal-body">
          {(recipientLabel || recipientNote || navigation) && (
            <div className="template-preview-toolbar">
              <div>
                {recipientLabel && <strong>{recipientLabel}</strong>}
                {recipientNote && <p className="muted small-note">{recipientNote}</p>}
              </div>
              {navigation && (
                <div className="button-row compact-actions template-preview-nav" aria-label="Preview message navigation">
                  <button type="button" className="version-arrow" onClick={navigation.onFirst} disabled={navigation.index <= 0} title="First message" aria-label="First message"><ArrowBigLeftDash aria-hidden="true" /></button>
                  <button type="button" className="version-arrow" onClick={navigation.onPrevious} disabled={navigation.index <= 0} title="Previous message" aria-label="Previous message"><ArrowBigLeft aria-hidden="true" /></button>
                  <span className="template-preview-count">{navigation.index + 1} / {navigation.total}</span>
                  <button type="button" className="version-arrow" onClick={navigation.onNext} disabled={navigation.index >= navigation.total - 1} title="Next message" aria-label="Next message"><ArrowBigRight aria-hidden="true" /></button>
                  <button type="button" className="version-arrow" onClick={navigation.onLast} disabled={navigation.index >= navigation.total - 1} title="Last message" aria-label="Last message"><ArrowBigRightDash aria-hidden="true" /></button>
                </div>
              )}
            </div>
          )}

          <MessageDisplayPanel
            title={shownSubject}
            fields={fields}
            bodyText={text}
            bodyHtml={html}
            preferredBodyMode={bodyMode}
            deriveTextFromHtml={false}
            attachments={attachments}
            emptyText="No message content is available."
          />

          {raw && (
            <details className="message-preview-raw">
              <summary>{rawLabel}</summary>
              <pre className="mock-message-raw">{raw}</pre>
            </details>
          )}
        </div>
        <footer className="modal-footer"><Button variant="primary" onClick={onClose}>{closeLabel}</Button></footer>
      </div>
    </div>
  );
}

function isEditableTarget(target: EventTarget | null): boolean {
  if (!(target instanceof HTMLElement)) return false;
  return target.isContentEditable || ["INPUT", "SELECT", "TEXTAREA"].includes(target.tagName);
}


export type MessagePreviewAttachment = CampaignMessagePreviewAttachment;
export type MessagePreviewMetaItem = CampaignMessagePreviewMetaItem;
export type MessagePreviewNavigation = CampaignMessagePreviewNavigation;
export type MessagePreviewOverlayProps = CampaignMessagePreviewOverlayProps;
