import { defineRouteConfig } from "@medusajs/admin-sdk"
import { CircleStackSolid, PencilSquare, EyeMini } from "@medusajs/icons"
import { Container, Heading, Button, Text, toast, FocusModal, Input, Label } from "@medusajs/ui"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { useState, useRef, useEffect, useCallback } from "react"
import { sdk } from "../../lib/sdk"
import { showConfirm } from "../../lib/confirm"
import { isDevOnlyFeaturesEnabled } from "../../lib/feature-flags"

export const config = isDevOnlyFeaturesEnabled ? defineRouteConfig({
  label: "adminRoutes.emailTemplates.layouts",
  translationNs: "translation",
  icon: CircleStackSolid,
  rank: 31,
}) : undefined

type Layout = { id: string; key: string; name: string; description: string | null; is_active: boolean; updated_at?: string }

const DEFAULT_LAYOUT_HTML = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="margin:0;padding:0;background-color:#f4f4f4;font-family:Arial,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#053f31;padding:40px 0;">
    <tr>
      <td align="center">
        <table width="520" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;padding:40px;max-width:520px;">
          <tr>
            <td style="padding-bottom:32px;">
              <span style="font-size:24px;font-weight:bold;color:#1a3a2a;">biomket</span>
            </td>
          </tr>
          <tr>
            <td>
              {{{body}}}
            </td>
          </tr>
          <tr>
            <td style="border-top:1px solid #eeeeee;padding-top:20px;margin-top:32px;">
              <p style="margin:0;color:#aaaaaa;font-size:12px;">
                Biomket — B2B Organic Waste Marketplace<br>
                <a href="mailto:info@biomket.com" style="color:#aaaaaa;">info@biomket.com</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`

export default function EmailLayoutsPage() {
  // Hide entire route in production
  if (!isDevOnlyFeaturesEnabled) {
    return null
  }

  const qc = useQueryClient()
  const [createOpen, setCreateOpen] = useState(false)
  const [editLayout, setEditLayout] = useState<Layout | null>(null)
  const [form, setForm] = useState({ key: "", name: "", description: "", html_content: DEFAULT_LAYOUT_HTML })
  const [mode, setMode] = useState<"edit" | "preview">("edit")
  const previewRef = useRef<HTMLIFrameElement>(null)

  const previewHtml = useCallback(() => {
    const placeholder = `
      <div style="padding: 40px; border: 2px dashed #e5e7eb; border-radius: 8px; color: #9ca3af; text-align: center; font-family: sans-serif;">
        <div style="font-size: 24px; margin-bottom: 8px;">📄</div>
        <div style="font-size: 14px; font-weight: 500;">Email Template Content</div>
        <div style="font-size: 12px; margin-top: 4px;"> This is where your template content will be injected via the {{{body}}} placeholder.</div>
      </div>
    `
    // Ensure we handle layout content even if it's currently empty or missing the placeholder
    const content = form.html_content || ""
    if (content.includes("{{{body}}}")) {
      return content.replace("{{{body}}}", placeholder)
    }
    
    // Fallback if placeholder is missing, just show the content + a warning at top
    return `
      <div style="background: #fff1f2; color: #991b1b; padding: 12px; font-family: sans-serif; font-size: 13px; border-bottom: 1px solid #fee2e2;">
        ⚠️ <strong>Missing {{{body}}} placeholder!</strong> Template content will not be injected.
      </div>
      ${content}
    `
  }, [form.html_content])

  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])

  const { data, isLoading } = useQuery({
    queryKey: ["email-layouts"],
    queryFn: async () => {
      const r = await sdk.fetch("/admin/email-layouts")
      if (!r.ok) throw new Error("Failed")
      return r.json() as Promise<{ layouts: Layout[]; count: number }>
    },
  })

  const saveMutation = useMutation({
    mutationFn: async () => {
      const url = editLayout ? `/admin/email-layouts/${editLayout.id}` : "/admin/email-layouts"
      console.log("Saving email layout to:", url)
      console.log("Form data:", form)

      const r = await sdk.fetch(url, {
        method: "POST",
        body: JSON.stringify(form),
        headers: { "Content-Type": "application/json" },
      })

      console.log("Response status:", r.status)

      if (!r.ok) {
        const errorText = await r.text()
        console.error("Save error:", errorText)
        throw new Error(errorText)
      }

      const result = await r.json()
      console.log("Save result:", result)
      return result
    },
    onSuccess: () => {
      console.log("Save success, invalidating queries")
      qc.invalidateQueries({ queryKey: ["email-layouts"] })
      toast.success(editLayout ? "Layout updated!" : "Layout created!")
      setCreateOpen(false)
      setEditLayout(null)
      setForm({ key: "", name: "", description: "", html_content: DEFAULT_LAYOUT_HTML })
    },
    onError: (e) => {
      console.error("Save mutation error:", e)
      toast.error((e as Error).message)
    },
  })

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const r = await sdk.fetch(`/admin/email-layouts/${id}`, { method: "DELETE" })
      if (!r.ok) throw new Error(await r.text())
    },
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["email-layouts"] }); toast.success("Layout deleted") },
    onError: (e) => toast.error((e as Error).message),
  })

  const openEdit = (l: Layout) => {
    setEditLayout(l)
    setForm({ key: l.key, name: l.name, description: l.description || "", html_content: "" })
    // Load full layout
    sdk.fetch(`/admin/email-layouts/${l.id}`).then((r) => r.json()).then((d: { layout: Layout & { html_content: string } }) => {
      setForm((f) => ({ ...f, html_content: d.layout.html_content }))
    })
    setCreateOpen(true)
  }

  const layouts = data?.layouts ?? []

  return (
    <Container className="px-3 sm:px-4">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-4 sm:py-6 gap-4">
        <div>
          <Heading level="h1">Email Layouts</Heading>
          <Text size="small" className="text-ui-fg-subtle mt-1">
            Base HTML wrappers shared across templates. Must contain {"{{{body}}}"} placeholder.
          </Text>
        </div>
        <Button size="small" onClick={() => { setEditLayout(null); setForm({ key: "", name: "", description: "", html_content: DEFAULT_LAYOUT_HTML }); setCreateOpen(true) }}>
          + New Layout
        </Button>
      </div>

      {isLoading && <p className="text-ui-fg-subtle text-center py-12">Loading...</p>}

      {!isLoading && layouts.length === 0 && (
        <Text className="text-ui-fg-subtle py-8 text-center">No layouts yet. Create one to share branding across templates.</Text>
      )}

      {!isLoading && layouts.length > 0 && (
        <div className="divide-y">
          {layouts.map((l) => (
            <div key={l.id} className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-3 gap-2">
              <div>
                <Text size="small" weight="plus" leading="compact">{l.name}</Text>
                <Text size="small" className="text-ui-fg-subtle">Key: {l.key}{l.description ? ` · ${l.description}` : ""}</Text>
              </div>
              <div className="flex gap-2">
                <Button size="small" variant="secondary" onClick={() => openEdit(l)}>Edit</Button>
                <Button size="small" variant="secondary" onClick={() =>
                  showConfirm({ title: "Delete layout?", text: "Templates using this layout will lose their branding wrapper." })
                    .then((r) => r.isConfirmed && deleteMutation.mutate(l.id))
                }>Delete</Button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create/Edit Modal */}
      <FocusModal open={createOpen} onOpenChange={(open) => { setCreateOpen(open); if (!open) setEditLayout(null) }}>
        <FocusModal.Content>
          <div className="flex h-full flex-col overflow-hidden">
            <FocusModal.Header>
              <div className="flex items-center justify-between gap-x-2">
                <Text weight="plus">{editLayout ? `Edit: ${editLayout.name}` : "New Layout"}</Text>
                <div className="flex gap-2">
                  <FocusModal.Close asChild>
                    <Button size="small" variant="secondary" disabled={saveMutation.isPending}>Cancel</Button>
                  </FocusModal.Close>
                  <Button size="small" onClick={() => saveMutation.mutate()} isLoading={saveMutation.isPending}>Save</Button>
                </div>
              </div>
            </FocusModal.Header>
            <FocusModal.Body className="flex-1 overflow-auto p-6">
              <div className="flex flex-col gap-4 max-w-4xl">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="flex flex-col gap-1.5">
                    <Label>Layout Key *</Label>
                    <Input placeholder="e.g. default" value={form.key} disabled={!!editLayout} onChange={(e) => setForm({ ...form, key: e.target.value })} />
                  </div>
                  <div className="flex flex-col gap-1.5">
                    <Label>Name *</Label>
                    <Input placeholder="Default Biomket Layout" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
                  </div>
                </div>
                <div className="flex flex-col gap-1.5">
                  <Label>Description</Label>
                  <Input placeholder="Optional description" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
                </div>
                <div className="flex flex-col gap-1.5 min-h-[500px]">
                  <div className="flex items-center justify-between">
                    <Label>HTML Content (must contain {"{{{body}}}"})</Label>
                    <div className="flex gap-1 bg-ui-bg-subtle p-1 rounded-md border">
                      <Button
                        size="small"
                        variant={mode === "edit" ? "primary" : "transparent"}
                        onClick={() => setMode("edit")}
                        className="h-7 px-2"
                      >
                        <PencilSquare className="mr-1" /> Edit
                      </Button>
                      <Button
                        size="small"
                        variant={mode === "preview" ? "primary" : "transparent"}
                        onClick={() => setMode("preview")}
                        className="h-7 px-2"
                      >
                        <EyeMini className="mr-1" /> Preview
                      </Button>
                    </div>
                  </div>
                  
                  <div className="bg-ui-bg-base border rounded-md overflow-hidden flex flex-col flex-1">
                    {mode === "edit" ? (
                      <div className="flex flex-col flex-1">
                        <div className="p-3 border-b bg-ui-bg-subtle">
                          <Text size="small" className="text-ui-fg-subtle">
                            ℹ️ Use {"{{{body}}}"} where template content will be injected.
                          </Text>
                        </div>
                        <textarea
                          value={form.html_content}
                          onChange={(e) => setForm({ ...form, html_content: e.target.value })}
                          className="flex-1 w-full p-4 font-mono text-sm min-h-[450px] outline-none bg-transparent resize-none"
                          spellCheck={false}
                          placeholder="<!DOCTYPE html>..."
                        />
                      </div>
                    ) : (
                      <div className="bg-ui-bg-subtle flex-1 flex flex-col min-h-[500px]">
                        <iframe
                          ref={previewRef}
                          title="Layout Preview"
                          className="w-full flex-1 border-none bg-white"
                          sandbox="allow-same-origin"
                        />
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </FocusModal.Body>
          </div>
        </FocusModal.Content>
      </FocusModal>
    </Container>
  )
}
