import { useState } from "react";
import { getBlockComponent } from "@/components/page-blocks";
import { SiteChromeFrame } from "@/components/SiteChromeFrame";
import type { PageBlock } from "@/admin/types";
import type { ComponentRecord } from "@/admin/types";
import type { ContentPlaceholderVars } from "@/lib/contentPlaceholders";
import {
  findComponentLibraryContent,
  resolveEditorBlockContent,
} from "@/lib/mergeBlockContent";
import type { PastePreviewSummary } from "@/lib/pasteComponent";
import { ComponentPreviewBySlug } from "../pages/ComponentPreviews";
import PastePreviewErrorBoundary from "./PastePreviewErrorBoundary";

type PasteComponentPreviewPanelProps = {
  block: PageBlock;
  summary: PastePreviewSummary;
  components: ComponentRecord[];
  placeholderVars: ContentPlaceholderVars;
  siteChromeKey: string;
  showGlobalFooter: boolean;
  placementLabel: string;
  warnings: string[];
};

export function PastePreviewSummaryCard({
  summary,
  placementLabel,
  warnings,
  showFallbackNote = false,
}: {
  summary: PastePreviewSummary;
  placementLabel: string;
  warnings: string[];
  showFallbackNote?: boolean;
}) {
  return (
    <div
      style={{
        padding: 16,
        background: "#f8fafc",
        border: "1px solid #e2e8f0",
        borderRadius: 12,
        fontSize: 14,
        lineHeight: 1.6,
        color: "#334155",
      }}
    >
      <p style={{ margin: "0 0 8px", fontWeight: 600 }}>Component summary</p>
      <ul style={{ margin: 0, paddingLeft: 20 }}>
        <li>
          <strong>Component:</strong> {summary.componentName}
        </li>
        <li>
          <strong>Fields found:</strong> {summary.fieldCount}
        </li>
        <li>
          <strong>Status:</strong> {summary.statusLabel}
        </li>
        <li>
          <strong>Placement:</strong> {placementLabel}
        </li>
        {summary.imageUrls.length > 0 && (
          <li>
            <strong>Images:</strong> {summary.imageUrls.length} found
          </li>
        )}
      </ul>
      {warnings.length > 0 && (
        <ul style={{ margin: "12px 0 0", paddingLeft: 20, color: "#b45309" }}>
          {warnings.map((warning) => (
            <li key={warning}>{warning}</li>
          ))}
        </ul>
      )}
      {showFallbackNote && (
        <p style={{ margin: "12px 0 0", fontSize: 13, color: "#64748b" }}>
          Layout preview could not be rendered. Review the summary above before applying.
        </p>
      )}
    </div>
  );
}

export default function PasteComponentPreviewPanel({
  block,
  summary,
  components,
  placeholderVars,
  siteChromeKey,
  showGlobalFooter,
  placementLabel,
  warnings,
}: PasteComponentPreviewPanelProps) {
  const [previewFailed, setPreviewFailed] = useState(false);
  const blockSlug = block.componentSlug ?? "";
  const BlockComp = getBlockComponent(blockSlug);
  const libraryContent = findComponentLibraryContent(block, components, blockSlug);
  const previewContent = resolveEditorBlockContent(block.content ?? {}, {
    blockSlug,
    libraryContent,
    pageVars: placeholderVars,
  });
  const showFooter = showGlobalFooter && blockSlug !== "footer";
  const canRenderLayout = Boolean(BlockComp || blockSlug) && !previewFailed;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
          gap: 12,
          padding: 14,
          background: summary.statusLabel === "Valid" ? "#f0fdf4" : "#fffbeb",
          border: `1px solid ${summary.statusLabel === "Valid" ? "#bbf7d0" : "#fde68a"}`,
          borderRadius: 12,
          fontSize: 13,
          color: "#334155",
        }}
      >
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", color: "#64748b" }}>Component</div>
          <div style={{ fontWeight: 600, marginTop: 4 }}>{summary.componentName}</div>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", color: "#64748b" }}>Fields found</div>
          <div style={{ fontWeight: 600, marginTop: 4 }}>{summary.fieldCount}</div>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", color: "#64748b" }}>Status</div>
          <div
            style={{
              fontWeight: 600,
              marginTop: 4,
              color: summary.statusLabel === "Valid" ? "#15803d" : "#b45309",
            }}
          >
            {summary.statusLabel}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", color: "#64748b" }}>Placement</div>
          <div style={{ fontWeight: 500, marginTop: 4 }}>{placementLabel}</div>
        </div>
      </div>

      {warnings.length > 0 && (
        <div
          style={{
            padding: "10px 14px",
            background: "#fffbeb",
            border: "1px solid #fde68a",
            borderRadius: 10,
            fontSize: 13,
            color: "#92400e",
          }}
        >
          <strong>Notes:</strong>
          <ul style={{ margin: "6px 0 0", paddingLeft: 18 }}>
            {warnings.map((warning) => (
              <li key={warning}>{warning}</li>
            ))}
          </ul>
        </div>
      )}

      {summary.imageUrls.length > 0 && (
        <div>
          <p style={{ margin: "0 0 8px", fontSize: 13, fontWeight: 600, color: "#334155" }}>Images in content</p>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {summary.imageUrls.map((url) => (
              <div
                key={url}
                style={{
                  width: 72,
                  height: 72,
                  borderRadius: 8,
                  overflow: "hidden",
                  border: "1px solid #e2e8f0",
                  background: "#f8fafc",
                }}
                title={url}
              >
                <img
                  src={url}
                  alt=""
                  style={{ width: "100%", height: "100%", objectFit: "cover" }}
                  onError={(event) => {
                    event.currentTarget.style.display = "none";
                  }}
                />
              </div>
            ))}
          </div>
        </div>
      )}

      <div>
        <p style={{ margin: "0 0 8px", fontSize: 13, fontWeight: 600, color: "#334155" }}>Layout preview</p>
        {canRenderLayout ? (
          <PastePreviewErrorBoundary onError={() => setPreviewFailed(true)}>
            <SiteChromeFrame
              key={siteChromeKey}
              previewMode
              showGlobalFooter={showFooter}
              className="rounded-xl overflow-hidden border border-slate-200"
            >
              <div style={{ padding: 16, maxHeight: 360, overflow: "auto", background: "#fff" }}>
                {BlockComp ? (
                  <BlockComp content={previewContent} />
                ) : (
                  <ComponentPreviewBySlug slug={blockSlug} content={previewContent} />
                )}
              </div>
            </SiteChromeFrame>
          </PastePreviewErrorBoundary>
        ) : (
          <PastePreviewSummaryCard
            summary={summary}
            placementLabel={placementLabel}
            warnings={warnings}
            showFallbackNote
          />
        )}
      </div>
    </div>
  );
}
