import { lazy, Suspense } from "react";
import { Download, X } from "lucide-react";
import {
  type DocumentEditorBackend,
  type DocumentEditorMode,
  type DocumentEditorPaneCollaborationConfig,
} from "../editor/document-editor-pane";
import { ArtifactPane, type ArtifactPaneProps } from "../primitives/artifact-pane";
import { detectFileFormat } from "./file-format";
import { FilePreview, type FilePreviewProps } from "./file-preview";
import { FileTabs, type FileTabData } from "./file-tabs";

const LazyDocumentEditorPane = lazy(async () => {
  const module = await import("../editor/document-editor-pane");
  return { default: module.DocumentEditorPane };
});

export interface FileArtifactPaneEditorOptions {
  enabled?: boolean;
  mode?: DocumentEditorMode;
  defaultMode?: DocumentEditorMode;
  onModeChange?: (mode: DocumentEditorMode) => void;
  backend?: DocumentEditorBackend;
  collaboration?: DocumentEditorPaneCollaborationConfig;
  placeholder?: string;
  autoFocus?: boolean;
  readOnly?: boolean;
  saving?: boolean;
  saveLabel?: string;
  onChange?: (markdown: string) => void;
  onSave?: (markdown: string) => Promise<void> | void;
  previewClassName?: string;
  editorClassName?: string;
}

export interface FileArtifactPaneProps extends Omit<FilePreviewProps, "className"> {
  path?: string;
  tabs?: FileTabData[];
  activeTabId?: string;
  onTabSelect?: (id: string) => void;
  onTabClose?: (id: string) => void;
  eyebrow?: ArtifactPaneProps["eyebrow"];
  meta?: ArtifactPaneProps["meta"];
  toolbar?: ArtifactPaneProps["toolbar"];
  footer?: ArtifactPaneProps["footer"];
  className?: string;
  headerClassName?: ArtifactPaneProps["headerClassName"];
  hideTitleBlock?: ArtifactPaneProps["hideTitleBlock"];
  editor?: FileArtifactPaneEditorOptions;
}

/**
 * FileArtifactPane — opinionated artifact frame for file previews with tabs and
 * header actions.
 */
export function FileArtifactPane({
  filename,
  content,
  blobUrl,
  mimeType,
  onClose,
  onDownload,
  path,
  tabs = [],
  activeTabId,
  onTabSelect,
  onTabClose,
  eyebrow = "Artifact",
  meta,
  toolbar,
  footer,
  className,
  headerClassName,
  hideTitleBlock,
  editor,
}: FileArtifactPaneProps) {
  const showTabs = tabs.length > 0 && onTabSelect && onTabClose;
  const paneTabs = showTabs ? (
    <FileTabs
      tabs={tabs}
      activeId={activeTabId}
      onSelect={onTabSelect}
      onClose={onTabClose}
    />
  ) : undefined;
  const isMarkdown =
    detectFileFormat(filename, mimeType) === "markdown" ||
    (path ? detectFileFormat(path, mimeType) === "markdown" : false);
  const isEditableMarkdown = isMarkdown && editor?.enabled;
  // Undefined (not an empty fragment) when there are no actions, so ArtifactPane
  // can collapse the header row entirely under hideTitleBlock.
  const headerActions = onDownload || onClose ? (
    <>
      {onDownload && (
        <button
          type="button"
          aria-label={`Download ${filename}`}
          onClick={onDownload}
          className="rounded-[var(--radius-sm)] p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60"
        >
          <Download className="h-4 w-4" />
        </button>
      )}
      {onClose && (
        <button
          type="button"
          aria-label={`Close ${filename}`}
          onClick={onClose}
          className="rounded-[var(--radius-sm)] p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60"
        >
          <X className="h-4 w-4" />
        </button>
      )}
    </>
  ) : undefined;

  if (isEditableMarkdown) {
    return (
      <Suspense
        fallback={(
          <ArtifactPane
            eyebrow={eyebrow}
            title={filename}
            subtitle={path}
            meta={meta}
            toolbar={toolbar}
            footer={footer}
            className={className}
            tabs={paneTabs}
            headerActions={headerActions}
            headerClassName={headerClassName}
            hideTitleBlock={hideTitleBlock}
          >
            <div className="flex min-h-[12rem] items-center justify-center rounded-[var(--radius-lg)] border border-dashed border-border bg-muted text-sm text-muted-foreground">
              Loading editor…
            </div>
          </ArtifactPane>
        )}
      >
        <LazyDocumentEditorPane
          eyebrow={eyebrow}
          title={filename}
          subtitle={path}
          meta={meta}
          toolbar={toolbar}
          footer={footer}
          className={className}
          tabs={paneTabs}
          headerActions={headerActions}
          headerClassName={headerClassName}
          hideTitleBlock={hideTitleBlock}
          markdown={content ?? ""}
          mode={editor.mode}
          defaultMode={editor.defaultMode}
          onModeChange={editor.onModeChange}
          backend={editor.backend}
          collaboration={editor.collaboration}
          placeholder={editor.placeholder}
          autoFocus={editor.autoFocus}
          readOnly={editor.readOnly}
          saving={editor.saving}
          saveLabel={editor.saveLabel}
          onChange={editor.onChange}
          onSave={editor.onSave}
          previewClassName={editor.previewClassName}
          editorClassName={editor.editorClassName}
        />
      </Suspense>
    );
  }

  return (
    <ArtifactPane
      eyebrow={eyebrow}
      title={filename}
      subtitle={path}
      meta={meta}
      toolbar={toolbar}
      footer={footer}
      className={className}
      tabs={paneTabs}
      headerActions={headerActions}
      headerClassName={headerClassName}
      hideTitleBlock={hideTitleBlock}
    >
      <FilePreview
        filename={filename}
        content={content}
        blobUrl={blobUrl}
        mimeType={mimeType}
        hideHeader={true}
      />
    </ArtifactPane>
  );
}
