import { createResource, createSignal, Show, For } from "solid-js";
import { useNavigate } from "@solidjs/router";
import AdminShell from "~/components/AdminShell";
import { api } from "~/lib/api";

interface EmailTemplate {
  name: string;
  subject: string;
  category: string;
  description: string;
}

export default function EmailManagementPage() {
  const [selectedTemplate, setSelectedTemplate] = createSignal<EmailTemplate | null>(null);
  const [previewHtml, setPreviewHtml] = createSignal("");
  const [testEmail, setTestEmail] = createSignal("");
  const [sending, setSending] = createSignal(false);
  const [message, setMessage] = createSignal("");

  const [templates] = createResource(async () => {
    const res = await api.get("/admin/email/templates");
    return res.data?.templates || [];
  });

  const groupedTemplates = () => {
    const groups: Record<string, EmailTemplate[]> = {};
    const all = templates() || [];
    all.forEach((t: EmailTemplate) => {
      if (!groups[t.category]) groups[t.category] = [];
      groups[t.category].push(t);
    });
    return groups;
  };

  const loadPreview = async (template: EmailTemplate) => {
    setSelectedTemplate(template);
    try {
      const res = await api.get(`/admin/email/templates/${template.name}/preview`);
      setPreviewHtml(res.data?.html || "");
    } catch (e) {
      setPreviewHtml("<p>Preview not available</p>");
    }
  };

  const sendTestEmail = async () => {
    if (!testEmail() || !selectedTemplate()) return;

    setSending(true);
    setMessage("");

    try {
      await api.post(`/admin/email/templates/${selectedTemplate()?.name}/test`, {
        to_email: testEmail(),
        template_name: selectedTemplate()?.name,
        variables: {
          first_name: "Test User",
          otp_code: "123456",
          package_name: "Test Package",
          amount_paid: "₹999",
          tracecoins_amount: "100",
        },
      });
      setMessage("✅ Test email sent successfully!");
      setTestEmail("");
    } catch (e: any) {
      setMessage("❌ Failed to send: " + (e.message || "Unknown error"));
    } finally {
      setSending(false);
    }
  };

  return (
    <AdminShell>
      <div class="p-6">
        <h1 class="text-2xl font-bold mb-6">📧 Email Management</h1>

        <Show when={message()}>
          <div
            class={`p-4 rounded-lg mb-4 ${message().includes("✅") ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"}`}
          >
            {message()}
          </div>
        </Show>

        <div class="grid lg:grid-cols-2 gap-6">
          {/* Template List */}
          <div class="bg-white rounded-xl border overflow-hidden">
            <div class="p-4 border-b bg-gray-50">
              <h2 class="font-semibold">Email Templates ({templates()?.length || 0})</h2>
            </div>

            <Show when={templates.loading}>
              <div class="p-8 text-center">
                <div class="animate-spin w-8 h-8 border-2 border-orange-500 border-t-transparent rounded-full mx-auto mb-4" />
                <p class="text-gray-500">Loading templates...</p>
              </div>
            </Show>

            <div class="max-h-[600px] overflow-y-auto">
              <For each={Object.entries(groupedTemplates())}>
                {([category, items]: [string, EmailTemplate[]]) => (
                  <div class="border-b last:border-b-0">
                    <div class="px-4 py-2 bg-gray-100 font-medium text-sm text-gray-700">
                      {category}
                    </div>
                    <For each={items}>
                      {(template: EmailTemplate) => (
                        <div
                          onClick={() => loadPreview(template)}
                          class={`p-4 cursor-pointer hover:bg-gray-50 transition-colors ${
                            selectedTemplate()?.name === template.name
                              ? "bg-orange-50 border-l-4 border-orange-500"
                              : "border-l-4 border-transparent"
                          }`}
                        >
                          <div class="flex justify-between items-start">
                            <div>
                              <h3 class="font-medium text-gray-900">{template.name}</h3>
                              <p class="text-sm text-gray-500">{template.subject}</p>
                            </div>
                            <button class="text-orange-600 text-sm hover:underline">Preview</button>
                          </div>
                          <p class="text-xs text-gray-400 mt-1">{template.description}</p>
                        </div>
                      )}
                    </For>
                  </div>
                )}
              </For>
            </div>
          </div>

          {/* Preview Panel */}
          <div class="space-y-6">
            <Show
              when={selectedTemplate()}
              fallback={
                <div class="bg-gray-50 rounded-xl p-12 text-center">
                  <div class="text-6xl mb-4">📧</div>
                  <p class="text-gray-500">Select a template to preview</p>
                </div>
              }
            >
              <div class="bg-white rounded-xl border overflow-hidden">
                <div class="p-4 border-b bg-gray-50 flex justify-between items-center">
                  <div>
                    <h2 class="font-semibold">{selectedTemplate()?.name}</h2>
                    <p class="text-sm text-gray-500">{selectedTemplate()?.subject}</p>
                  </div>
                  <span class="px-3 py-1 bg-orange-100 text-orange-800 text-xs rounded-full">
                    {selectedTemplate()?.category}
                  </span>
                </div>

                {/* Email Preview */}
                <div class="p-4">
                  <div class="border rounded-lg overflow-hidden">
                    <div class="bg-gray-100 p-2 text-xs text-gray-500 border-b">Preview</div>
                    <iframe
                      srcdoc={previewHtml()}
                      class="w-full h-[400px]"
                      sandbox="allow-same-origin"
                    />
                  </div>
                </div>

                {/* Test Email Section */}
                <div class="p-4 border-t bg-gray-50">
                  <h3 class="font-medium mb-3">Send Test Email</h3>
                  <div class="flex gap-3">
                    <input
                      type="email"
                      placeholder="Enter test email address"
                      value={testEmail()}
                      onInput={(e) => setTestEmail(e.currentTarget.value)}
                      class="flex-1 px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                    />
                    <button
                      onClick={sendTestEmail}
                      disabled={!testEmail() || sending()}
                      class="px-6 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <Show when={sending()} fallback="Send Test">
                        <span class="flex items-center gap-2">
                          <span class="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full" />
                          Sending...
                        </span>
                      </Show>
                    </button>
                  </div>
                  <p class="text-xs text-gray-500 mt-2">
                    Test emails will include sample data for preview purposes.
                  </p>
                </div>

                {/* Template Variables */}
                <div class="p-4 border-t">
                  <h3 class="font-medium mb-2">Template Variables</h3>
                  <div class="flex flex-wrap gap-2">
                    <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">
                      first_name
                    </span>
                    <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">
                      dashboard_url
                    </span>
                    <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">...</span>
                  </div>
                </div>
              </div>
            </Show>
          </div>
        </div>

        {/* Email Stats Summary */}
        <div class="mt-8 grid grid-cols-4 gap-4">
          <div class="bg-white p-6 rounded-xl border">
            <div class="text-3xl font-bold text-orange-600">35</div>
            <div class="text-sm text-gray-500">Total Templates</div>
          </div>
          <div class="bg-white p-6 rounded-xl border">
            <div class="text-3xl font-bold text-green-600">6</div>
            <div class="text-sm text-gray-500">Categories</div>
          </div>
          <div class="bg-white p-6 rounded-xl border">
            <div class="text-3xl font-bold text-blue-600">100%</div>
            <div class="text-sm text-gray-500">Branded</div>
          </div>
          <div class="bg-white p-6 rounded-xl border">
            <div class="text-3xl font-bold text-purple-600">Mobile</div>
            <div class="text-sm text-gray-500">Responsive</div>
          </div>
        </div>
      </div>
    </AdminShell>
  );
}
