import {
  Container,
  Heading,
  Button,
  Text,
  Input,
  Label,
  Select,
  Textarea,
  Badge,
  toast,
  FocusModal,
} from "@medusajs/ui"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { useNavigate, useSearchParams } from "react-router-dom"
import { useState, useEffect, useRef, useCallback } from "react"
import { sdk } from "../../../lib/sdk"
import { mergeTemplateIntoLayout, normalizeLayoutKey } from "../../../lib/email-renderer"
import { useTranslation } from "react-i18next"
import {
  EyeMini,
  PencilSquare,
  ArrowLeftMini,
  ArrowPathMini,
  CheckCircleSolid,
} from "@medusajs/icons"
import { isDevOnlyFeaturesEnabled } from "../../../lib/feature-flags"

// ─── Types ───────────────────────────────────────────────────────────────────

type Layout = { id: string; key: string; name: string }

type Template = {
  id: string
  key: string
  name: string
  description: string
  subject: string
  html_content: string
  category: string
  variables: string[] | Record<string, unknown> | null
  layout_key: string | null
  version: number
  is_active: boolean
}

type TemplateResponse = {
  template: Template
  is_production_mode?: boolean
}

const isBundledProduction = false

const lockedFieldStyle = {
  background: "var(--medusa-bg-field)",
  color: "var(--medusa-fg-base)",
  borderColor: "var(--medusa-border-base)",
  cursor: "default",
  opacity: 1,
  WebkitTextFillColor: "var(--medusa-fg-base)",
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function parseVariables(raw: Template["variables"]): string {
  if (!raw) return ""
  if (Array.isArray(raw)) return raw.join(", ")
  if (typeof raw === "object") return Object.keys(raw).join(", ")
  return String(raw)
}

/**
 * Replace {{variable}} tokens in a string using the given data map.
 * Unknown variables are left highlighted in the preview.
 */
function renderHandlebars(template: string, data: Record<string, string>): string {
  const applyValue = (match: string, key: string) => {
    const trimmed = key.trim()
    const value = data[trimmed]
    if (value !== undefined) return value
    return `<mark style="background:#fde68a;padding:0 2px;border-radius:2px">${match}</mark>`
  }

  const withRawBlocks = template.replace(/\{\{\{(\s*[\w.]+\s*)\}\}\}/g, (match, key) =>
    applyValue(match, key)
  )

  return withRawBlocks.replace(/\{\{(\s*[\w.]+\s*)\}\}/g, (match, key) =>
    applyValue(match, key)
  )
}

function buildDefaultSampleData(variables: string): Record<string, string> {
  // Comprehensive defaults for all common Biomket template variables
  const defaults: Record<string, string> = {
    // Customer identity
    customer_name: "John Doe",
    first_name: "John",
    last_name: "Doe",
    full_name: "John Doe",
    email: "john.doe@example.com",
    customer_email: "john.doe@example.com",
    customer_id: "cus_01HXYZ",
    company_name: "Biomket Ltd",
    // Auth / links
    reset_url: "https://example.com/reset?token=abc123",
    login_url: "https://example.com/login",
    confirm_url: "https://example.com/confirm?token=abc123",
    verify_url: "https://example.com/verify?token=abc123",
    activation_url: "https://example.com/activate?token=abc123",
    unsubscribe_url: "https://example.com/unsubscribe",
    dashboard_url: "https://example.com/dashboard",
    // Orders
    order_id: "ORD-001",
    order_number: "#1001",
    order_total: "$1,250.00",
    captured_amount: "$1,250.00",
    payment_id: "pay_01TESTPAYMENT",
    item_count: "3",
    order_items_html: `<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:20px 0 8px;">
  <tr><td style="padding:12px 0;border-bottom:1px solid #eeeeee;"><div style="font-size:15px;color:#1f2937;font-weight:600;">Organic Compost</div><div style="color:#6b7280;font-size:13px;">Quantity: 2</div></td></tr>
  <tr><td style="padding:12px 0;border-bottom:1px solid #eeeeee;"><div style="font-size:15px;color:#1f2937;font-weight:600;">Bio Fertilizer</div><div style="color:#6b7280;font-size:13px;">Quantity: 1</div></td></tr>
</table>`,
    shipping_methods_html: `<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 20px;">
  <tr><td style="padding-bottom:10px;font-size:15px;font-weight:700;color:#1a3a2a;">Selected shipping option</td></tr>
  <tr><td style="padding:10px 0;border-bottom:1px solid #eeeeee;font-size:14px;color:#1f2937;">Standard Transport - $50.00</td></tr>
</table>`,
    shipping_option_names: "Standard Transport",
    order_date: "2026-03-31",
    order_status: "Confirmed",
    order_url: "https://example.com/orders/ORD-001",
    // Shipping
    tracking_number: "TRK-9876543210",
    tracking_url: "https://track.example.com/TRK-9876543210",
    shipping_address: "123 Main St, Mumbai, MH 400001",
    estimated_delivery: "April 5, 2026",
    carrier: "FedEx",
    // Products
    product_name: "Organic Compost",
    product_sku: "SKU-12345",
    quantity: "5",
    unit: "kg",
    // Payments / invoices
    invoice_url: "https://example.com/invoice/001",
    invoice_number: "INV-001",
    amount: "$1,250.00",
    payment_method: "Bank Transfer",
    due_date: "April 15, 2026",
    // Support
    support_email: process.env.SUPPORT_EMAIL ?? "support@biomket.com",
    support_url: "https://example.com/support",
    // Misc
    site_name: "Biomket",
    site_url: "https://biomket.com",
    year: new Date().getFullYear().toString(),
  }

  const result: Record<string, string> = {}
  variables
    .split(",")
    .map((v) => v.trim())
    .filter(Boolean)
    .forEach((v) => {
      if (defaults[v] !== undefined) {
        result[v] = defaults[v]
      } else {
        // Smart fallback: generate a readable example based on variable name
        const lower = v.toLowerCase()
        if (lower.includes("url") || lower.includes("link")) {
          result[v] = `https://example.com/${v.replace(/_/g, "-")}`
        } else if (lower.includes("email")) {
          result[v] = "example@email.com"
        } else if (lower.includes("date") || lower.includes("at")) {
          result[v] = new Date().toLocaleDateString("en-IN")
        } else if (lower.includes("total") || lower.includes("amount") || lower.includes("price")) {
          result[v] = "$100.00"
        } else if (lower.includes("name")) {
          result[v] = "Sample Name"
        } else if (lower.includes("id") || lower.includes("number")) {
          result[v] = "12345"
        } else {
          result[v] = `Sample ${v.replace(/_/g, " ")}`
        }
      }
    })
  return result
}

// ─── Smart defaults for new templates ────────────────────────────────────────

const SMART_DEFAULTS: Record<string, Partial<Template> & { variables: string[] }> = {
  "password-reset": {
    name: "Password Reset",
    category: "user",
    subject: "Reset your Biomket password",
    variables: ["customer_name", "reset_url", "site_name", "support_email", "year"],
    html_content: `<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
  <h2>Password Reset</h2>
  <p>Hi {{customer_name}},</p>
  <p>We received a request to reset your {{site_name}} password. Click the button below to choose a new one:</p>
  <p>
    <a href="{{reset_url}}" style="display:inline-block;background:#4f46e5;color:#fff;padding:12px 24px;border-radius:6px;text-decoration:none">
      Reset Password
    </a>
  </p>
  <p>This link expires in <strong>15 minutes</strong>. If you didn't request a reset, you can safely ignore this email.</p>
  <p>Need help? Contact <a href="mailto:{{support_email}}">{{support_email}}</a>.</p>
  <p style="color:#6b7280;font-size:12px">&copy; {{year}} {{site_name}}</p>
</div>`,
  },
  welcome: {
    name: "Welcome Email",
    category: "user",
    subject: "Welcome to Biomket, {{customer_name}}!",
    variables: ["customer_name", "company_name", "dashboard_url", "site_name", "support_email", "year"],
    html_content: `<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
  <h2>Welcome to Biomket 🌱</h2>
  <p>Hi {{customer_name}},</p>
  <p>Thank you for joining Biomket – the B2B Organic Waste Marketplace. We're excited to have you on board.</p>
  <p>Your account for {{company_name}} has been created successfully.</p>
  <p>You can now browse suppliers, place orders, and manage your account from the dashboard.</p>
  <p>
    <a href="{{dashboard_url}}" style="display:inline-block;background:#4f46e5;color:#fff;padding:12px 24px;border-radius:6px;text-decoration:none">
      Open Dashboard
    </a>
  </p>
  <p>If you need help getting started, contact <a href="mailto:{{support_email}}">{{support_email}}</a>.</p>
  <p style="color:#6b7280;font-size:12px">&copy; {{year}} {{site_name}}</p>
</div>`,
  },
  "order-confirmation": {
    name: "Order Confirmation",
    category: "order",
    subject: "Your Biomket Order #{{order_id}} is confirmed",
    variables: ["customer_name", "order_id", "order_total", "item_count", "order_items_html", "shipping_methods_html", "shipping_option_names", "site_name", "support_email", "year"],
    html_content: `<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
  <h2>Order Confirmed ✓</h2>
  <p>Hi {{customer_name}},</p>
  <p>Your order <strong>#{{order_id}}</strong> has been confirmed.</p>
  <p>Order Total: <strong>{{order_total}}</strong></p>
  <p>Items: <strong>{{item_count}}</strong></p>
  {{{order_items_html}}}
  {{{shipping_methods_html}}}
  <p>Shipping option selected: <strong>{{shipping_option_names}}</strong></p>
  <p>We'll send you another email when your order ships.</p>
  <p>Questions? Contact <a href="mailto:{{support_email}}">{{support_email}}</a>.</p>
  <p style="color:#6b7280;font-size:12px">&copy; {{year}} {{site_name}}</p>
</div>`,
  },
  "payment-success": {
    name: "Payment Success",
    category: "payment",
    subject: "Payment received for Biomket Order #{{order_id}}",
    variables: ["customer_name", "order_id", "payment_id", "captured_amount", "order_total", "order_items_html", "shipping_methods_html", "shipping_option_names", "site_name", "support_email", "year"],
    html_content: `<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
  <h2>Payment Received</h2>
  <p>Hi {{customer_name}},</p>
  <p>We successfully captured your payment for order <strong>#{{order_id}}</strong>.</p>
  <p>Captured Amount: <strong>{{captured_amount}}</strong></p>
  <p>Order Total: <strong>{{order_total}}</strong></p>
  <p>Payment Reference: <strong>{{payment_id}}</strong></p>
  {{{order_items_html}}}
  {{{shipping_methods_html}}}
  <p>Shipping option selected: <strong>{{shipping_option_names}}</strong></p>
  <p>Questions? Contact <a href="mailto:{{support_email}}">{{support_email}}</a>.</p>
  <p style="color:#6b7280;font-size:12px">&copy; {{year}} {{site_name}}</p>
</div>`,
  },
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function EmailTemplateEditPage() {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const qc = useQueryClient()
  const templateId = searchParams.get("id")
  const isNew = searchParams.get("new") === "1"
  const requestedMode = searchParams.get("mode")

  // ── Form state
  const [form, setForm] = useState({
    key: "",
    name: "",
    description: "",
    subject: "",
    html_content: "",
    category: "user",
    variables: "",
    layout_key: "",
    is_active: true,
  })

  // ── Editor / preview state
  const [mode, setMode] = useState<"edit" | "preview">(
    requestedMode === "preview" ? "preview" : "edit"
  )
  const [sampleData, setSampleData] = useState<string>("")
  const [sampleDataError, setSampleDataError] = useState("")
  const [testOpen, setTestOpen] = useState(false)
  const [testEmail, setTestEmail] = useState("")
  const [testData, setTestData] = useState("{}")
  const [testLoading, setTestLoading] = useState(false)

  const previewRef = useRef<HTMLIFrameElement>(null)

  // ── Load existing template
  const { data: templateData, isLoading: templateLoading } = useQuery({
    queryKey: ["email-template", templateId],
    queryFn: async () => {
      const r = await sdk.fetch(`/admin/email-templates/${templateId}`)
      if (!r.ok) throw new Error("Failed to load template")
      return r.json() as Promise<TemplateResponse>
    },
    enabled: !!templateId && !isNew,
  })

  const isProductionMode = Boolean(templateData?.is_production_mode) || isBundledProduction
  const isEditingLocked = isProductionMode
  const isMetadataLocked = isEditingLocked

  // ── Load layouts
  const { data: layoutsData } = useQuery({
    queryKey: ["email-layouts"],
    queryFn: async () => {
      const r = await sdk.fetch("/admin/email-layouts")
      if (!r.ok) return { layouts: [] }
      return r.json() as Promise<{ layouts: Layout[] }>
    },
  })

  const layouts = layoutsData?.layouts ?? []
  const selectedLayout = layouts.find(
    (layout) => normalizeLayoutKey(layout.key) === normalizeLayoutKey(form.layout_key)
  )

  const { data: selectedLayoutData } = useQuery({
    queryKey: ["email-layout", selectedLayout?.id],
    queryFn: async () => {
      const r = await sdk.fetch(`/admin/email-layouts/${selectedLayout?.id}`)
      if (!r.ok) throw new Error("Failed to load layout")
      return r.json() as Promise<{ layout: Layout & { html_content: string } }>
    },
    enabled: !!selectedLayout?.id,
  })

  // ── Hydrate form from fetched template
  useEffect(() => {
    if (templateData?.template) {
      const t = templateData.template
      const vars = parseVariables(t.variables)
      setForm({
        key: t.key,
        name: t.name,
        description: t.description || "",
        subject: t.subject,
        html_content: t.html_content,
        category: t.category,
        variables: vars,
        layout_key: normalizeLayoutKey(t.layout_key) || "",
        is_active: t.is_active,
      })
      // Auto-build sample data from known variables
      const defaults = buildDefaultSampleData(vars)
      setSampleData(JSON.stringify(defaults, null, 2))
      setTestData(JSON.stringify(defaults, null, 2))
    }
  }, [templateData])

  // ── Sync test data when variables change (new template)
  useEffect(() => {
    if (isNew && form.variables) {
      const defaults = buildDefaultSampleData(form.variables)
      setSampleData(JSON.stringify(defaults, null, 2))
      setTestData(JSON.stringify(defaults, null, 2))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form.variables, isNew])

  // ── Smart defaults when key is typed for new templates
  const applySmartDefault = useCallback(
    (key: string) => {
      const defaults = SMART_DEFAULTS[key]
      if (defaults && isNew) {
        const vars = Array.isArray(defaults.variables)
          ? defaults.variables.join(", ")
          : ""
        setForm((f) => ({
          ...f,
          key,
          name: defaults.name || f.name,
          subject: defaults.subject || f.subject,
          html_content: defaults.html_content || f.html_content,
          category: defaults.category || f.category,
          variables: vars || f.variables,
        }))
      } else {
        setForm((f) => ({ ...f, key }))
      }
    },
    [isNew]
  )

  // ── Computed preview HTML
  const previewHtml = useCallback(() => {
    let data: Record<string, string> = {}
    try {
      const parsed = JSON.parse(sampleData || "{}")
      // Flatten to string values for rendering
      Object.entries(parsed).forEach(([k, v]) => {
        data[k] = String(v)
      })
      setSampleDataError("")
    } catch {
      setSampleDataError("Invalid JSON — fix the sample data to see preview")
    }
    const templateHtml = selectedLayoutData?.layout?.html_content
      ? mergeTemplateIntoLayout(selectedLayoutData.layout.html_content, form.html_content)
      : form.html_content
    const rendered = renderHandlebars(templateHtml, data)
    return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  body { margin: 0; padding: 20px; background: #f9f9f9; font-family: Arial, sans-serif; font-size: 14px; }
  * { box-sizing: border-box; }
</style>
</head>
<body>${rendered}</body>
</html>`
  }, [form.html_content, sampleData, selectedLayoutData?.layout?.html_content])

  // ── Refresh iframe when preview mode is active
  useEffect(() => {
    if (mode === "preview" && previewRef.current) {
      const html = previewHtml()
      const blob = new Blob([html], { type: "text/html" })
      const url = URL.createObjectURL(blob)
      previewRef.current.src = url
      return () => URL.revokeObjectURL(url)
    }
  }, [mode, previewHtml])

  // ── Save mutation
  const saveMutation = useMutation({
    mutationFn: async () => {
      const payload = {
        ...form,
        variables: form.variables
          ? form.variables
              .split(",")
              .map((v) => v.trim())
              .filter(Boolean)
          : [],
        layout_key: normalizeLayoutKey(form.layout_key) || null,
      }
      const url = isNew
        ? "/admin/email-templates"
        : `/admin/email-templates/${templateId}`
      const r = await sdk.fetch(url, {
        method: "POST",
        body: JSON.stringify(payload),
        headers: { "Content-Type": "application/json" },
      })
      if (!r.ok) throw new Error(await r.text())
      return r.json()
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["email-templates"] })
      qc.invalidateQueries({ queryKey: ["email-template", templateId] })
      toast.success(isNew ? "Template created!" : "Template saved!")
      navigate("/email-templates")
    },
    onError: (e) => toast.error((e as Error).message),
  })

  // ── Send test email
  const sendTest = async () => {
    setTestLoading(true)
    try {
      let sData: Record<string, unknown> = {}
      try {
        sData = JSON.parse(testData)
      } catch {
        /* ignore */
      }
      const r = await sdk.fetch("/admin/email-templates/test", {
        method: "POST",
        body: JSON.stringify({
          template_id: templateId,
          send_to: testEmail,
          sample_data: sData,
        }),
        headers: { "Content-Type": "application/json" },
      })
      const json = (await r.json()) as {
        success: boolean
        message_id?: string
        message?: string
        warning?: string
      }
      if (json.success) {
        toast.success(`Test email sent! ${json.warning ? "⚠️ " + json.warning : ""}`)
        setTestOpen(false)
      } else {
        toast.success(json.message || json.warning || "Test email could not be sent")
      }
    } catch (e) {
      toast.success("Test email request could not be completed")
    } finally {
      setTestLoading(false)
    }
  }

  // ── Parsed variable list
  const variableList = form.variables
    ? form.variables
        .split(",")
        .map((v) => v.trim())
        .filter(Boolean)
    : []

  if (templateLoading) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "40vh" }}>
        <Text className="text-ui-fg-subtle">Loading template…</Text>
      </div>
    )
  }

  const currentVersion = templateData?.template?.version

  return (
    <Container style={{ maxWidth: 960, margin: "0 auto", paddingBottom: 80 }}>
      {/* ── Header ── */}
      <div
        style={{
          display: "flex",
          flexWrap: "wrap",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 12,
          padding: "24px 0 20px",
          borderBottom: "1px solid var(--medusa-border-base)",
          marginBottom: 24,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <button
            onClick={() => navigate("/email-templates")}
            style={{
              background: "none",
              border: "none",
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: 4,
              color: "var(--medusa-fg-subtle)",
              padding: "4px 6px",
              borderRadius: 6,
            }}
          >
            <ArrowLeftMini />
            <Text size="small">{t("adminRoutes.emailTemplates.title")}</Text>
          </button>
          <Text size="small" className="text-ui-fg-muted">/</Text>
          <Heading level="h1" style={{ fontSize: 18, margin: 0 }}>
            {isNew
              ? t("adminRoutes.emailTemplates.newTemplate")
              : form.name || t("adminRoutes.emailTemplates.editTemplate")}
          </Heading>
          {isDevOnlyFeaturesEnabled && currentVersion && (
            <Badge color="grey" size="2xsmall">
              v{currentVersion}
            </Badge>
          )}
          {form.is_active && !isNew && (
            <Badge color="green" size="2xsmall">
              <CheckCircleSolid style={{ width: 10, height: 10, marginRight: 2 }} />
              {t("adminRoutes.emailTemplates.active")}
            </Badge>
          )}
        </div>

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {!isNew && (
            <>
              {isDevOnlyFeaturesEnabled && <Button
                size="small"
                variant="secondary"
                onClick={() => navigate(`/email-templates/history?id=${templateId}`)}
              >
                <ArrowPathMini />
                {t("adminRoutes.emailTemplates.history")}
              </Button>}
              <Button
                size="small"
                variant="secondary"
                onClick={() => setTestOpen(true)}
                disabled={isEditingLocked}
              >
                📧 {t("adminRoutes.emailTemplates.testEmail")}
              </Button>
            </>
          )}
          <Button size="small" variant="secondary" onClick={() => navigate("/email-templates")}>
            {t("adminRoutes.common.cancel")}
          </Button>
          <Button
            size="small"
            onClick={() => saveMutation.mutate()}
            isLoading={saveMutation.isPending}
            disabled={
              isEditingLocked ||
              saveMutation.isPending ||
              !form.name ||
              !form.key ||
              !form.subject
            }
          >
            {isNew ? t("adminRoutes.emailTemplates.createTemplate") : t("adminRoutes.emailTemplates.saveChanges")}
          </Button>
        </div>
      </div>

      {/* ── Version bump notice ── */}
      {isDevOnlyFeaturesEnabled && !isNew && currentVersion && (
        <div
          style={{
            background: "var(--medusa-bg-component)",
            border: "1px solid var(--medusa-border-base)",
            borderRadius: 8,
            padding: "10px 16px",
            marginBottom: 20,
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          <Text size="small" className="text-ui-fg-subtle">
            Saving will snapshot the current version v{currentVersion} and create{" "}
            <strong>v{currentVersion + 1}</strong>. Previous versions can be restored from History.
          </Text>
        </div>
      )}

      {isEditingLocked && (
        <div
          style={{
            background: "var(--medusa-bg-component)",
            border: "1px solid var(--medusa-border-base)",
            borderRadius: 8,
            padding: "10px 16px",
            marginBottom: 20,
          }}
        >
            <Text size="small" className="text-ui-fg-subtle">
            In production mode, email templates are view-only. All fields and save actions are disabled.
          </Text>
        </div>
      )}

      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        {/* ── Section 1: Basic Info ── */}
        <section
          style={{
            background: "var(--medusa-bg-component)",
            border: "1px solid var(--medusa-border-base)",
            borderRadius: 8,
            padding: 24,
          }}
        >
          <Text size="small" weight="plus" leading="compact" style={{ marginBottom: 16 }}>
            {t("adminRoutes.emailTemplates.basicInformation")}
          </Text>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            {/* Template Key */}
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <Label htmlFor="tpl-key">
                {t("adminRoutes.emailTemplates.fields.slug")} <span style={{ color: "var(--medusa-fg-error)" }}>*</span>
              </Label>
              <Input
                id="tpl-key"
                placeholder={t("adminRoutes.emailTemplates.slugPlaceholder")}
                value={form.key}
                disabled={!isNew || !isDevOnlyFeaturesEnabled}
                readOnly={!isNew || !isDevOnlyFeaturesEnabled}
                style={!isNew || !isDevOnlyFeaturesEnabled ? lockedFieldStyle : undefined}
                onChange={(e) => applySmartDefault(e.target.value)}
              />
              {isNew && (
                <Text size="small" className="text-ui-fg-subtle">
                  {t("adminRoutes.emailTemplates.slugHint")}
                </Text>
              )}
              {isNew && SMART_DEFAULTS[form.key] && (
                <Text size="small" style={{ color: "var(--medusa-fg-interactive)" }}>
                  ✨ Smart defaults applied for "{form.key}"
                </Text>
              )}
            </div>

            {/* Template Name */}
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <Label htmlFor="tpl-name">
                {t("adminRoutes.emailTemplates.fields.title")} <span style={{ color: "var(--medusa-fg-error)" }}>*</span>
              </Label>
              <Input
                id="tpl-name"
                placeholder={t("adminRoutes.emailTemplates.titlePlaceholder")}
                value={form.name}
                disabled={!isDevOnlyFeaturesEnabled}
                readOnly={!isDevOnlyFeaturesEnabled}
                style={!isDevOnlyFeaturesEnabled ? lockedFieldStyle : undefined}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
              />
            </div>

            {/* Category */}
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <Label htmlFor="tpl-category">Category</Label>
              <Select
                value={form.category}
                disabled={!isDevOnlyFeaturesEnabled}
                onValueChange={(v) => setForm({ ...form, category: v })}
              >
                <Select.Trigger id="tpl-category" style={!isDevOnlyFeaturesEnabled ? lockedFieldStyle : undefined}>
                  <Select.Value />
                </Select.Trigger>
                <Select.Content>
                  {["user", "order", "payment", "admin"].map((c) => (
                    <Select.Item key={c} value={c}>
                      {c.charAt(0).toUpperCase() + c.slice(1)}
                    </Select.Item>
                  ))}
                </Select.Content>
              </Select>
            </div>

            {/* Layout */}
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <Label htmlFor="tpl-layout">Layout (optional)</Label>
              <Select
                value={form.layout_key || "__none__"}
                disabled={!isDevOnlyFeaturesEnabled}
                onValueChange={(v) =>
                  setForm({ ...form, layout_key: v === "__none__" ? "" : v })
                }
              >
                <Select.Trigger id="tpl-layout" style={!isDevOnlyFeaturesEnabled ? lockedFieldStyle : undefined}>
                  <Select.Value placeholder="No layout" />
                </Select.Trigger>
                <Select.Content>
                  <Select.Item value="__none__">No layout</Select.Item>
                  {layouts.map((l) => (
                    <Select.Item key={l.key} value={l.key}>
                      {l.name}
                    </Select.Item>
                  ))}
                </Select.Content>
              </Select>
            </div>
          </div>

          {/* Description */}
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 16 }}>
            <Label htmlFor="tpl-desc">{t("adminRoutes.emailTemplates.fields.description")}</Label>
            <Input
              id="tpl-desc"
              placeholder="Brief description of when this email is sent"
              value={form.description}
              disabled={!isDevOnlyFeaturesEnabled}
              readOnly={!isDevOnlyFeaturesEnabled}
              style={!isDevOnlyFeaturesEnabled ? lockedFieldStyle : undefined}
              onChange={(e) => setForm({ ...form, description: e.target.value })}
            />
          </div>

          {/* Variables */}
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 16 }}>
            <Label htmlFor="tpl-vars">Expected Variables</Label>
            <Input
              id="tpl-vars"
              placeholder="customer_name, reset_url, order_id"
              value={form.variables}
              disabled={!isDevOnlyFeaturesEnabled}
              readOnly={!isDevOnlyFeaturesEnabled}
              style={!isDevOnlyFeaturesEnabled ? lockedFieldStyle : undefined}
              onChange={(e) => setForm({ ...form, variables: e.target.value })}
            />
            <Text size="small" className="text-ui-fg-subtle">
              Comma-separated. Use{" "}
              <code
                style={{
                  background: "var(--medusa-bg-base)",
                  padding: "1px 4px",
                  borderRadius: 3,
                  fontFamily: "monospace",
                }}
              >
                {"{{variable_name}}"}
              </code>{" "}
              in your subject and body.
            </Text>
            {variableList.length > 0 && (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 4 }}>
                {variableList.map((v) => (
                  <Badge key={v} color="blue" size="2xsmall">
                    {`{{${v}}}`}
                  </Badge>
                ))}
              </div>
            )}
          </div>
        </section>

        {/* ── Section 2: Subject ── */}
        <section
          style={{
            background: "var(--medusa-bg-component)",
            border: "1px solid var(--medusa-border-base)",
            borderRadius: 8,
            padding: 24,
          }}
        >
          <Text size="small" weight="plus" leading="compact" style={{ marginBottom: 16 }}>
            Email Subject{" "}
            <span style={{ color: "var(--medusa-fg-error)" }}>*</span>
          </Text>
          <Input
            id="tpl-subject"
            placeholder='e.g. Reset your password, or "Hello {{customer_name}}"'
            value={form.subject}
            disabled={!isDevOnlyFeaturesEnabled && isMetadataLocked}
            readOnly={!isDevOnlyFeaturesEnabled && isMetadataLocked}
            style={!isDevOnlyFeaturesEnabled && isMetadataLocked ? lockedFieldStyle : undefined}
            onChange={(e) => setForm({ ...form, subject: e.target.value })}
          />
          <Text size="small" className="text-ui-fg-subtle" style={{ marginTop: 6 }}>
            You can use{" "}
            <code style={{ fontFamily: "monospace" }}>{"{{variable}}"}</code> tokens in the
            subject line too.
          </Text>
        </section>

        {/* ── Section 3: HTML Body Editor + Preview ── */}
        <section
          style={{
            background: "var(--medusa-bg-component)",
            border: "1px solid var(--medusa-border-base)",
            borderRadius: 8,
            overflow: "hidden",
          }}
        >
          {/* Toolbar */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              padding: "14px 20px",
              borderBottom: "1px solid var(--medusa-border-base)",
              background: "var(--medusa-bg-base)",
            }}
          >
            <Text size="small" weight="plus" leading="compact">
              {mode === "edit" ? "HTML Body" : "Live Preview"}
            </Text>

            <div style={{ display: "flex", gap: 6 }}>
              <Button
                size="small"
                variant={mode === "edit" ? "primary" : "secondary"}
                onClick={() => setMode("edit")}
              >
                <PencilSquare />
                Edit
              </Button>
              <Button
                size="small"
                variant={mode === "preview" ? "primary" : "secondary"}
                onClick={() => setMode("preview")}
              >
                <EyeMini />
                Preview
              </Button>
            </div>
          </div>

          {/* Editor */}
          {mode === "edit" && (
            <div style={{ padding: 20 }}>
              {variableList.length > 0 && (
                <div
                  style={{
                    display: "flex",
                    flexWrap: "wrap",
                    gap: 4,
                    marginBottom: 12,
                    padding: "8px 12px",
                    background: "var(--medusa-bg-base)",
                    borderRadius: 6,
                    border: "1px solid var(--medusa-border-base)",
                  }}
                >
                  <Text size="small" className="text-ui-fg-subtle" style={{ marginRight: 6, whiteSpace: "nowrap" }}>
                    Available:
                  </Text>
                  {variableList.map((v) => (
                    <Badge key={v} color="blue" size="2xsmall" style={{ cursor: "default" }}>
                      {`{{${v}}}`}
                    </Badge>
                  ))}
                </div>
              )}
              <textarea
                id="tpl-body"
                value={form.html_content}
                onChange={(e) => setForm({ ...form, html_content: e.target.value })}
                disabled={!isDevOnlyFeaturesEnabled && isEditingLocked}
                readOnly={!isDevOnlyFeaturesEnabled && isEditingLocked}
                spellCheck={false}
                style={{
                  width: "100%",
                  minHeight: 420,
                  padding: 14,
                  fontFamily: "'Courier New', Courier, monospace",
                  fontSize: 13,
                  lineHeight: 1.6,
                  background: (!isDevOnlyFeaturesEnabled && isEditingLocked) ? "var(--medusa-bg-disabled)" : "var(--medusa-bg-base)",
                  color: (!isDevOnlyFeaturesEnabled && isEditingLocked) ? "var(--medusa-fg-disabled)" : "var(--medusa-fg-base)",
                  border: "1px solid var(--medusa-border-base)",
                  borderRadius: 6,
                  resize: "vertical",
                  outline: "none",
                  boxSizing: "border-box",
                  whiteSpace: "pre",
                  overflowX: "auto",
                  transition: "border-color 0.15s",
                }}
                onFocus={(e) => {
                  if (!(!isDevOnlyFeaturesEnabled && isEditingLocked)) {
                    e.currentTarget.style.borderColor = "var(--medusa-fg-interactive)"
                  }
                }}
                onBlur={(e) => {
                  e.currentTarget.style.borderColor = "var(--medusa-border-base)"
                }}
                placeholder="<p>Hi {{customer_name}},</p><p>Your message here...</p>"
              />
              <Text size="small" className="text-ui-fg-subtle" style={{ marginTop: 8 }}>
                Write standard HTML. Use{" "}
                <code style={{ fontFamily: "monospace" }}>{"{{variable}}"}</code> tokens for dynamic content.
              </Text>
            </div>
          )}

          {/* Preview */}
          {mode === "preview" && (
            <div>
              {sampleDataError && (
                <div
                  style={{
                    padding: "10px 20px",
                    background: "#fef2f2",
                    borderBottom: "1px solid #fecaca",
                  }}
                >
                  <Text size="small" style={{ color: "var(--medusa-fg-error)" }}>
                    ⚠️ {sampleDataError}
                  </Text>
                </div>
              )}

              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "auto 1fr",
                  gap: 0,
                  minHeight: 500,
                }}
              >
                {/* Sample data sidebar */}
                <div
                  style={{
                    width: 260,
                    borderRight: "1px solid var(--medusa-border-base)",
                    padding: 16,
                    background: "var(--medusa-bg-base)",
                  }}
                >
                  <Text
                    size="small"
                    weight="plus"
                    leading="compact"
                    style={{ marginBottom: 8, display: "block" }}
                  >
                    Sample Data
                  </Text>
                  <Text size="small" className="text-ui-fg-subtle" style={{ marginBottom: 8, display: "block" }}>
                    Edit JSON below to test variable substitution:
                  </Text>
                  <textarea
                    value={sampleData}
                    onChange={(e) => setSampleData(e.target.value)}
                    disabled={isEditingLocked}
                    readOnly={isEditingLocked}
                    spellCheck={false}
                    style={{
                      width: "100%",
                      height: 380,
                      padding: 10,
                      fontFamily: "'Courier New', Courier, monospace",
                      fontSize: 11,
                      lineHeight: 1.5,
                      background: isEditingLocked ? "var(--medusa-bg-disabled)" : "var(--medusa-bg-component)",
                      color: isEditingLocked ? "var(--medusa-fg-disabled)" : "var(--medusa-fg-base)",
                      border: "1px solid var(--medusa-border-base)",
                      borderRadius: 6,
                      resize: "vertical",
                      outline: "none",
                      boxSizing: "border-box",
                    }}
                    onFocus={(e) => {
                      if (!isEditingLocked) {
                        e.currentTarget.style.borderColor = "var(--medusa-fg-interactive)"
                      }
                    }}
                    onBlur={(e) => {
                      e.currentTarget.style.borderColor = "var(--medusa-border-base)"
                    }}
                  />
                  {variableList.length > 0 && (
                    <div style={{ marginTop: 8 }}>
                      <Text
                        size="small"
                        className="text-ui-fg-subtle"
                        style={{ marginBottom: 4, display: "block" }}
                      >
                        Variables in template:
                      </Text>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 3 }}>
                        {variableList.map((v) => (
                          <Badge key={v} color="blue" size="2xsmall">
                            {v}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                  <div
                    style={{
                      marginTop: 10,
                      padding: "8px 10px",
                      background: "var(--medusa-bg-component)",
                      borderRadius: 6,
                      border: "1px solid var(--medusa-border-base)",
                    }}
                  >
                    <Text size="small" className="text-ui-fg-subtle">
                      <mark style={{ background: "#fde68a", padding: "0 3px", borderRadius: 2, color: "#000" }}>
                        Yellow highlights
                      </mark>{" "}
                      = missing variables
                    </Text>
                  </div>
                </div>

                {/* Email preview iframe */}
                <div style={{ background: "#e5e7eb", padding: 20, minHeight: 500 }}>
                  <div
                    style={{
                      background: "#fff",
                      borderRadius: 6,
                      boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
                      overflow: "hidden",
                      minHeight: 460,
                    }}
                  >
                    {/* Mock email chrome */}
                    <div
                      style={{
                        background: "#f3f4f6",
                        borderBottom: "1px solid #e5e7eb",
                        padding: "10px 16px",
                      }}
                    >
                      <Text size="small" className="text-ui-fg-subtle">
                        <strong>Subject:</strong>{" "}
                        {form.subject
                          ? renderHandlebars(
                              form.subject,
                              Object.fromEntries(
                                Object.entries(
                                  (() => {
                                    try { return JSON.parse(sampleData || "{}") } catch { return {} }
                                  })()
                                ).map(([k, v]) => [k, String(v)])
                              )
                            )
                          : "(no subject)"}
                      </Text>
                    </div>
                    <iframe
                      ref={previewRef}
                      title="Email Preview"
                      style={{
                        width: "100%",
                        height: 1000,
                        border: "none",
                        display: "block",
                      }}
                      sandbox="allow-same-origin"
                    />
                  </div>
                </div>
              </div>
            </div>
          )}
        </section>
      </div>

      {/* ── Test Email Modal ── */}
      <FocusModal open={testOpen} onOpenChange={setTestOpen}>
        <FocusModal.Content>
          <div style={{ display: "flex", height: "100%", flexDirection: "column", overflow: "hidden" }}>
            <FocusModal.Header>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                <Text weight="plus">📧 Send Test Email</Text>
                <div style={{ display: "flex", gap: 8 }}>
                  <FocusModal.Close asChild>
                    <Button size="small" variant="secondary">
                      Cancel
                    </Button>
                  </FocusModal.Close>
                  <Button
                    size="small"
                    onClick={sendTest}
                    isLoading={testLoading}
                    disabled={isEditingLocked || !testEmail || testLoading}
                  >
                    Send Test
                  </Button>
                </div>
              </div>
            </FocusModal.Header>
            <FocusModal.Body style={{ flex: 1, overflow: "auto", padding: 24 }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 20, maxWidth: 520 }}>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  <Label htmlFor="test-email">
                    Send to <span style={{ color: "var(--medusa-fg-error)" }}>*</span>
                  </Label>
                  <Input
                    id="test-email"
                    type="email"
                    placeholder="admin@example.com"
                    value={testEmail}
                    disabled={isEditingLocked}
                    readOnly={isEditingLocked}
                    onChange={(e) => setTestEmail(e.target.value)}
                  />
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  <Label htmlFor="test-data">Sample Data (JSON)</Label>
                  <Textarea
                    id="test-data"
                    rows={10}
                    value={testData}
                    disabled={isEditingLocked}
                    readOnly={isEditingLocked}
                    onChange={(e) => setTestData(e.target.value)}
                    placeholder={'{\n  "customer_name": "Test User",\n  "reset_url": "https://example.com/reset?token=abc"\n}'}
                    className="font-mono text-sm"
                  />
                  <Text size="small" className="text-ui-fg-subtle">
                    These values will replace{" "}
                    <code style={{ fontFamily: "monospace" }}>{"{{variables}}"}</code> in the
                    template before sending.
                  </Text>
                </div>
                {form.variables && (
                  <div
                    style={{
                      background: "var(--medusa-bg-base)",
                      padding: "12px 16px",
                      borderRadius: 8,
                      border: "1px solid var(--medusa-border-base)",
                    }}
                  >
                    <Text size="small" weight="plus" style={{ marginBottom: 8, display: "block" }}>
                      Expected variables:
                    </Text>
                    <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                      {variableList.map((v) => (
                        <Badge key={v} color="blue" size="2xsmall">
                          {`{{${v}}}`}
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </FocusModal.Body>
          </div>
        </FocusModal.Content>
      </FocusModal>
    </Container>
  )
}
