"use client";

import { ActionIcon, Box, Group, SegmentedControl, Text, Tooltip } from "@mantine/core";
import {
  IconDeviceDesktop,
  IconDeviceMobile,
  IconExternalLink,
  IconMaximize,
  IconMinimize,
  IconRefresh,
} from "@tabler/icons-react";
import React, { useMemo, useState } from "react";

interface Props {
  html: string;
  /** Values substituted into {{placeholders}} so the preview reads like an email. */
  sampleData: Record<string, string>;
  fullscreen?: boolean;
  onToggleFullscreen?: () => void;
}

const WIDTHS = { desktop: "100%", mobile: "375px" } as const;

/**
 * Live render of the template being edited.
 *
 * Substitution here is a deliberate approximation, not the real renderer: it
 * fills simple {{name}} placeholders so the preview reads like an email instead
 * of a form letter full of braces. Block helpers ({{#if}}, {{#each}}) are left
 * untouched — faking them in the browser would show a layout that the server
 * may not produce, which is worse than showing the raw tag. Use Test send for
 * output you can trust.
 */
export function WorkspacePreview({ html, sampleData, fullscreen, onToggleFullscreen }: Props) {
  const [device, setDevice] = useState<keyof typeof WIDTHS>("desktop");
  const [nonce, setNonce] = useState(0);

  const rendered = useMemo(() => {
    let out = html;
    for (const [key, value] of Object.entries(sampleData)) {
      // Only simple placeholders; anything with #, /, or a space is a helper.
      out = out.replace(new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`, "g"), value);
    }
    return out;
  }, [html, sampleData]);

  const unresolved = useMemo(() => {
    const found = new Set<string>();
    for (const m of rendered.matchAll(/\{\{\s*([^#/{}][^{}]*?)\s*\}\}/g)) {
      const name = (m[1] ?? "").trim();
      if (name && !name.includes(" ")) found.add(name);
    }
    return [...found];
  }, [rendered]);

  return (
    <Box style={{ height: "100%", display: "flex", flexDirection: "column" }}>
      <Group justify="space-between" px="sm" py={6} style={{ borderBottom: "1px solid var(--mantine-color-gray-3)" }}>
        <Text size="xs" fw={600} c="dimmed">PREVIEW</Text>
        <Group gap={6}>
          <SegmentedControl
            size="xs"
            value={device}
            onChange={(v) => setDevice(v as keyof typeof WIDTHS)}
            data={[
              { value: "desktop", label: <IconDeviceDesktop size={13} /> },
              { value: "mobile", label: <IconDeviceMobile size={13} /> },
            ]}
          />
          <Tooltip label="Re-render">
            <ActionIcon size="sm" variant="subtle" onClick={() => setNonce((n) => n + 1)}>
              <IconRefresh size={13} />
            </ActionIcon>
          </Tooltip>
          <Tooltip label="Open in a new browser tab">
            <ActionIcon
              size="sm"
              variant="subtle"
              onClick={() => {
                // Hand off through localStorage rather than the URL: an email
                // is far past any practical query-string limit, and this reuses
                // the viewer the template detail page already opens.
                localStorage.setItem("edm_preview_html", rendered);
                window.open("/admin/edm/preview", "_blank");
              }}
            >
              <IconExternalLink size={13} />
            </ActionIcon>
          </Tooltip>
          {onToggleFullscreen && (
            <Tooltip label={fullscreen ? "Exit full screen (Esc)" : "Full screen"}>
              <ActionIcon size="sm" variant="subtle" onClick={onToggleFullscreen}>
                {fullscreen ? <IconMinimize size={13} /> : <IconMaximize size={13} />}
              </ActionIcon>
            </Tooltip>
          )}
        </Group>
      </Group>

      {unresolved.length > 0 && (
        <Text size="xs" c="dimmed" px="sm" py={4} style={{ borderBottom: "1px solid var(--mantine-color-gray-2)" }}>
          Unfilled: {unresolved.slice(0, 6).join(", ")}
          {unresolved.length > 6 ? ` +${unresolved.length - 6}` : ""}
        </Text>
      )}

      <Box style={{ flex: 1, overflow: "auto", backgroundColor: "var(--mantine-color-gray-2)", padding: 8 }}>
        <iframe
          key={`${device}-${nonce}`}
          title="EDM preview"
          srcDoc={rendered}
          // Sandboxed with no allow-scripts: template html is author-supplied
          // and this renders inside an authenticated console page, so it must
          // not be able to run script or reach back into the parent document.
          sandbox=""
          style={{
            width: WIDTHS[device],
            maxWidth: "100%",
            height: "100%",
            minHeight: 400,
            border: "none",
            backgroundColor: "#fff",
            margin: "0 auto",
            display: "block",
          }}
        />
      </Box>
    </Box>
  );
}
