"use client";

import { useState } from "react";
import { useLivePreview } from "@payloadcms/live-preview-react";
import {
  renderOrderConfirmationHtml,
  renderPasswordResetHtml,
  renderOrderStatusHtml,
  renderBackInStockHtml,
  ORDER_STATUS_EMAIL_ICON,
  SAMPLE_ORDER,
  SAMPLE_ORDER_MANUAL,
  type EmailTemplateContent,
} from "../../../lib/emailTemplates";
import type { EmailTemplateType } from "../../../lib/payload";

const PAYLOAD_URL = process.env.NEXT_PUBLIC_PAYLOAD_URL || "https://payload.mk360.de";

// Same useLivePreview() mechanism as LivePostContent.tsx (blog) — connects
// to the Payload admin's iframe via postMessage and updates `data` as the
// admin edits fields, no save required. Renders through the exact same
// renderOrderConfirmationHtml/renderPasswordResetHtml functions that build
// the real sent email (app/lib/orderEmail.ts, Customers.ts's forgotPassword
// hook on the Payload side uses its own simple template instead — see that
// hook's own comment on why the two aren't pixel-identical for
// password-reset specifically) — order-confirmation previews exactly.
export function LiveEmailPreviewClient({
  type,
  initialTemplate,
}: {
  type: EmailTemplateType;
  initialTemplate: EmailTemplateContent;
}) {
  const { data } = useLivePreview<EmailTemplateContent>({
    initialData: initialTemplate,
    serverURL: PAYLOAD_URL,
    depth: 0,
  });

  // Only order-confirmation has two meaningfully different rendered
  // states (isManualPayment true/false change which blocks show at all,
  // not just text) — every other type has one sample and no toggle.
  const [sampleVariant, setSampleVariant] = useState<"paid" | "manual">("paid");
  const orderSample = sampleVariant === "paid" ? SAMPLE_ORDER : SAMPLE_ORDER_MANUAL;

  // No real company-settings fetch in this preview context — passing null
  // falls back to DEFAULT_LEGAL_FOOTER_LINES (placeholder Anbieterkennzeichnung)
  // inside buildLegalFooterLines(), same shape as the real send just with
  // placeholder business data.
  const html =
    type === "order-confirmation"
      ? renderOrderConfirmationHtml(data, orderSample, null)
      : type === "password-reset"
        ? renderPasswordResetHtml(data, "https://einfach-produktiv.mk360.de/konto/passwort-zuruecksetzen?token=beispiel-token", null)
        : type === "back-in-stock"
          ? renderBackInStockHtml(
              data,
              "ToDo-Karten – Set",
              "https://einfach-produktiv.mk360.de/todo-cards",
              null,
              "https://payload.mk360.de/api/media/file/product-todo-karten.png",
            )
          : renderOrderStatusHtml(
              data,
              ORDER_STATUS_EMAIL_ICON[type] ?? "✓",
              SAMPLE_ORDER.orderNumber,
              `https://einfach-produktiv.mk360.de/konto/bestellungen/${encodeURIComponent(SAMPLE_ORDER.orderNumber)}`,
              null,
            );

  return (
    <div style={{ background: "#f4f2ee", minHeight: "100vh", padding: "32px 0" }}>
      {type === "order-confirmation" && (
        <div style={{ display: "flex", justifyContent: "center", gap: 8, marginBottom: 16 }}>
          <button
            type="button"
            onClick={() => setSampleVariant("paid")}
            style={{
              padding: "8px 16px",
              borderRadius: 999,
              border: "1px solid #d1cec4",
              background: sampleVariant === "paid" ? "#f6a701" : "#fff",
              fontWeight: 700,
              fontSize: 13,
              cursor: "pointer",
            }}
          >
            Online bezahlt
          </button>
          <button
            type="button"
            onClick={() => setSampleVariant("manual")}
            style={{
              padding: "8px 16px",
              borderRadius: 999,
              border: "1px solid #d1cec4",
              background: sampleVariant === "manual" ? "#f6a701" : "#fff",
              fontWeight: 700,
              fontSize: 13,
              cursor: "pointer",
            }}
          >
            Vorkasse (Überweisung)
          </button>
        </div>
      )}
      {/* An iframe, not dangerouslySetInnerHTML into a plain div — `html`
          here is a full `<body>...</body>` fragment (see emailTemplates.ts's
          emailShell()), meant to become an actual email document. Dropped
          directly into this page's own already-existing <body> via
          dangerouslySetInnerHTML, that's a nested <body> tag — invalid
          HTML the browser "fixes" unpredictably, which is why this preview
          used to render broken (wrong background/padding/font, inline
          styles not applying). An iframe gives the email HTML its own
          real document, exactly like an actual email client would. */}
      <iframe
        srcDoc={`<!DOCTYPE html><html>${html}</html>`}
        title="E-Mail-Vorschau"
        style={{ width: "100%", height: "100vh", border: "none", display: "block" }}
      />
    </div>
  );
}
