"use client";
import { useEffect, useRef, useState } from "react";
import * as XLSX from "xlsx";
import { Upload, Send, TestTube, Save, Bold, Link2, Image as ImageIcon, Trash2 } from "lucide-react";

type Recipient = { name: string; email: string };

export default function EmailCampaignPage() {
  // SMTP settings
  const [smtpHost, setSmtpHost] = useState("");
  const [smtpPort, setSmtpPort] = useState("465");
  const [smtpUser, setSmtpUser] = useState("");
  const [smtpFrom, setSmtpFrom] = useState("");
  const [smtpPass, setSmtpPass] = useState("");
  const [hasPassword, setHasPassword] = useState(false);
  const [savingSmtp, setSavingSmtp] = useState(false);
  const [smtpSaved, setSmtpSaved] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{ ok: boolean; error?: string } | null>(null);

  // Recipients
  const [recipients, setRecipients] = useState<Recipient[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [savedLists, setSavedLists] = useState<{ id: string; name: string; count: number }[]>([]);
  const [saveListName, setSaveListName] = useState("");

  // Compose
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const bodyRef = useRef<HTMLTextAreaElement>(null);
  const templateInputRef = useRef<HTMLInputElement>(null);

  // Test email
  const [testEmail, setTestEmail] = useState("");
  const [sendingTest, setSendingTest] = useState(false);
  const [testSendResult, setTestSendResult] = useState<{ ok: boolean; error?: string } | null>(null);

  // Send
  const [sending, setSending] = useState(false);
  const [sendResult, setSendResult] = useState<{ total: number; successCount: number; results: any[] } | null>(null);

  useEffect(() => {
    fetch("/api/admin/email-campaign/smtp-settings")
      .then((r) => r.json())
      .then((d) => {
        setSmtpHost(d.smtp_host || "");
        setSmtpPort(d.smtp_port || "465");
        setSmtpUser(d.smtp_user || "");
        setSmtpFrom(d.smtp_from || "");
        setHasPassword(d.hasPassword);
      });
    loadSavedLists();
  }, []);

  async function loadSavedLists() {
    const res = await fetch("/api/admin/email-campaign/lists");
    setSavedLists(await res.json());
  }

  async function saveSmtp() {
    setSavingSmtp(true);
    setSmtpSaved(false);
    await fetch("/api/admin/email-campaign/smtp-settings", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ smtp_host: smtpHost, smtp_port: smtpPort, smtp_user: smtpUser, smtp_from: smtpFrom, smtp_pass: smtpPass }),
    });
    setSmtpPass("");
    setSavingSmtp(false);
    setSmtpSaved(true);
    if (smtpPass) setHasPassword(true);
  }

  async function runTest() {
    setTesting(true);
    setTestResult(null);
    const res = await fetch("/api/admin/email-campaign/test-smtp", { method: "POST" });
    setTestResult(await res.json());
    setTesting(false);
  }

  function handleExcelUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (evt) => {
      const data = new Uint8Array(evt.target?.result as ArrayBuffer);
      const workbook = XLSX.read(data, { type: "array" });
      const sheet = workbook.Sheets[workbook.SheetNames[0]];
      const rows: any[] = XLSX.utils.sheet_to_json(sheet);

      const parsed: Recipient[] = rows
        .map((row) => {
          // Try to find name/email columns regardless of exact header casing.
          const keys = Object.keys(row);
          const emailKey = keys.find((k) => k.toLowerCase().includes("email"));
          const nameKey = keys.find((k) => k.toLowerCase().includes("name"));
          return {
            email: emailKey ? String(row[emailKey]).trim() : "",
            name: nameKey ? String(row[nameKey]).trim() : "",
          };
        })
        .filter((r) => r.email && r.email.includes("@"));

      setRecipients((prev) => [...prev, ...parsed]);
    };
    reader.readAsArrayBuffer(file);
    e.target.value = "";
  }

  function removeRecipient(index: number) {
    setRecipients((prev) => prev.filter((_, i) => i !== index));
  }

  async function saveCurrentList() {
    if (!saveListName.trim() || recipients.length === 0) return;
    await fetch("/api/admin/email-campaign/lists", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: saveListName, recipients }),
    });
    setSaveListName("");
    loadSavedLists();
  }

  async function loadList(id: string) {
    const res = await fetch(`/api/admin/email-campaign/lists/${id}`);
    const data = await res.json();
    setRecipients((prev) => [...prev, ...data.recipients]);
  }

  async function deleteList(id: string) {
    if (!confirm("Delete this saved list?")) return;
    await fetch(`/api/admin/email-campaign/lists/${id}`, { method: "DELETE" });
    loadSavedLists();
  }

  function insertFormatting(before: string, after: string = "") {
    const textarea = bodyRef.current;
    if (!textarea) return;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selected = body.slice(start, end) || "text";
    const newBody = body.slice(0, start) + before + selected + after + body.slice(end);
    setBody(newBody);
  }

  function insertLink() {
    const url = prompt("Link URL:");
    if (!url) return;
    insertFormatting(`<a href="${url}" style="color:#dc2626;">`, "</a>");
  }

  function insertImage() {
    const url = prompt("Image URL:");
    if (!url) return;
    setBody((b) => b + `\n<img src="${url}" style="max-width:100%;border-radius:8px;" />\n`);
  }

  function handleTemplateImport(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (evt) => {
      const text = evt.target?.result as string;
      setBody(text);
    };
    reader.readAsText(file);
    e.target.value = "";
  }

  async function sendTestEmail() {
    if (!testEmail.trim() || !subject.trim() || !body.trim()) return;
    setSendingTest(true);
    setTestSendResult(null);
    const res = await fetch("/api/admin/email-campaign/send-test", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: testEmail, subject, html: body }),
    });
    const data = await res.json();
    setSendingTest(false);
    setTestSendResult({ ok: res.ok, error: data.error });
  }

  async function sendCampaign() {
    if (!subject.trim() || !body.trim() || recipients.length === 0) return;
    if (!confirm(`Send this email to ${recipients.length} recipient(s)?`)) return;
    setSending(true);
    setSendResult(null);
    const res = await fetch("/api/admin/email-campaign/send", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ subject, html: body, recipients }),
    });
    const data = await res.json();
    setSending(false);
    if (res.ok) setSendResult(data);
    else alert(data.error || "Send failed.");
  }

  const inputCls = "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600";

  return (
    <div className="max-w-4xl">
      <h2 className="text-lg font-semibold mb-1">Email Campaign</h2>
      <p className="text-xs text-neutral-500 mb-6">
        Send a bulk email to a list of recipients — import from Excel, compose with basic formatting, and send.
        Emails use Resend if configured, otherwise the SMTP settings below.
      </p>

      {/* SMTP Settings */}
      <div className="card p-5 mb-6">
        <h3 className="font-semibold mb-3">SMTP Settings</h3>
        <div className="grid sm:grid-cols-2 gap-3 mb-3">
          <div>
            <label className="block text-xs text-neutral-500 mb-1">Host</label>
            <input value={smtpHost} onChange={(e) => setSmtpHost(e.target.value)} placeholder="mail.yourdomain.com" className={inputCls} />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1">Port</label>
            <input value={smtpPort} onChange={(e) => setSmtpPort(e.target.value)} placeholder="465" className={inputCls} />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1">Username</label>
            <input value={smtpUser} onChange={(e) => setSmtpUser(e.target.value)} placeholder="noreply@yourdomain.com" className={inputCls} />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1">
              Password {hasPassword && <span className="text-green-500">(saved — leave blank to keep it)</span>}
            </label>
            <input type="password" value={smtpPass} onChange={(e) => setSmtpPass(e.target.value)} placeholder={hasPassword ? "••••••••" : ""} className={inputCls} />
          </div>
          <div className="sm:col-span-2">
            <label className="block text-xs text-neutral-500 mb-1">From address</label>
            <input value={smtpFrom} onChange={(e) => setSmtpFrom(e.target.value)} placeholder="noreply@yourdomain.com" className={inputCls} />
          </div>
        </div>
        <div className="flex items-center gap-3 flex-wrap">
          <button onClick={saveSmtp} disabled={savingSmtp} className="btn-primary px-4 py-2 text-sm flex items-center gap-2">
            <Save size={14} /> {savingSmtp ? "Saving..." : "Save SMTP Settings"}
          </button>
          <button onClick={runTest} disabled={testing} className="btn-secondary px-4 py-2 text-sm flex items-center gap-2">
            <TestTube size={14} /> {testing ? "Testing..." : "Test SMTP Connection"}
          </button>
          {smtpSaved && <span className="text-green-500 text-sm">✓ Saved</span>}
          {testResult && (
            <span className={`text-sm ${testResult.ok ? "text-green-500" : "text-red-500"}`}>
              {testResult.ok ? "✓ Connection successful" : `✗ ${testResult.error}`}
            </span>
          )}
        </div>
      </div>

      {/* Recipients */}
      <div className="card p-5 mb-6">
        <h3 className="font-semibold mb-3">Recipients ({recipients.length})</h3>

        <input ref={fileInputRef} type="file" accept=".xlsx,.xls,.csv" className="hidden" onChange={handleExcelUpload} />
        <div className="flex items-center gap-3 mb-4 flex-wrap">
          <button onClick={() => fileInputRef.current?.click()} className="btn-secondary px-4 py-2 text-sm flex items-center gap-2">
            <Upload size={14} /> Import from Excel
          </button>
          <p className="text-xs text-neutral-600">Needs columns with "name" and "email" in the header (any casing).</p>
        </div>

        {savedLists.length > 0 && (
          <div className="mb-4">
            <p className="text-xs text-neutral-500 mb-2">Saved lists:</p>
            <div className="flex flex-wrap gap-2">
              {savedLists.map((l) => (
                <div key={l.id} className="flex items-center gap-1 bg-neutral-900 border border-neutral-800 rounded-full pl-3 pr-1 py-1">
                  <button onClick={() => loadList(l.id)} className="text-xs hover:text-red-400">
                    {l.name} ({l.count})
                  </button>
                  <button onClick={() => deleteList(l.id)} className="text-neutral-600 hover:text-red-500 p-1">
                    <Trash2 size={12} />
                  </button>
                </div>
              ))}
            </div>
          </div>
        )}

        {recipients.length > 0 && (
          <>
            <div className="max-h-48 overflow-y-auto border border-neutral-800 rounded-md mb-3">
              <table className="w-full text-xs">
                <thead className="bg-neutral-900 text-neutral-500 text-left sticky top-0">
                  <tr><th className="p-2">Name</th><th className="p-2">Email</th><th className="p-2"></th></tr>
                </thead>
                <tbody>
                  {recipients.map((r, i) => (
                    <tr key={i} className="border-t border-neutral-900">
                      <td className="p-2">{r.name || "—"}</td>
                      <td className="p-2">{r.email}</td>
                      <td className="p-2 text-right">
                        <button onClick={() => removeRecipient(i)} className="text-neutral-600 hover:text-red-500">
                          <Trash2 size={12} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="flex items-center gap-2">
              <input value={saveListName} onChange={(e) => setSaveListName(e.target.value)} placeholder="Save this list as..." className={`${inputCls} flex-1`} />
              <button onClick={saveCurrentList} className="btn-secondary px-4 py-2 text-sm shrink-0">Save List</button>
            </div>
          </>
        )}
      </div>

      {/* Compose */}
      <div className="card p-5 mb-6">
        <div className="flex items-center justify-between mb-3">
          <h3 className="font-semibold">Compose</h3>
          <div>
            <input ref={templateInputRef} type="file" accept=".html,.htm,.txt" className="hidden" onChange={handleTemplateImport} />
            <button
              type="button"
              onClick={() => templateInputRef.current?.click()}
              className="btn-secondary px-3 py-1.5 text-xs flex items-center gap-1.5"
            >
              <Upload size={12} /> Import HTML Template
            </button>
          </div>
        </div>
        <p className="text-xs text-neutral-600 mb-3">
          Use <code>{"{{name}}"}</code> and <code>{"{{email}}"}</code> to personalize each email automatically.
        </p>
        <div className="mb-3">
          <label className="block text-xs text-neutral-500 mb-1">Subject</label>
          <input value={subject} onChange={(e) => setSubject(e.target.value)} className={inputCls} />
        </div>
        <div>
          <label className="block text-xs text-neutral-500 mb-1">Body (HTML)</label>
          <div className="flex gap-1 mb-1">
            <button type="button" onClick={() => insertFormatting("<b>", "</b>")} className="p-2 rounded hover:bg-neutral-800" title="Bold"><Bold size={14} /></button>
            <button type="button" onClick={insertLink} className="p-2 rounded hover:bg-neutral-800" title="Insert link"><Link2 size={14} /></button>
            <button type="button" onClick={insertImage} className="p-2 rounded hover:bg-neutral-800" title="Insert image"><ImageIcon size={14} /></button>
          </div>
          <textarea ref={bodyRef} value={body} onChange={(e) => setBody(e.target.value)} rows={8} className={inputCls} />
        </div>

        {body && (
          <div className="mt-3">
            <p className="text-xs text-neutral-500 mb-1">Preview:</p>
            <div className="border border-neutral-800 rounded-md p-4 bg-white text-black" dangerouslySetInnerHTML={{ __html: body }} />
          </div>
        )}
      </div>

      {/* Send Test Email */}
      <div className="card p-5 mb-6">
        <h3 className="font-semibold mb-1">Send Test Email</h3>
        <p className="text-xs text-neutral-500 mb-3">
          Send this draft to a single address before sending it to your full recipient list — subject line
          gets prefixed with "[TEST]" so it's obvious in your inbox.
        </p>
        <div className="flex items-center gap-2 flex-wrap">
          <input
            type="email"
            value={testEmail}
            onChange={(e) => setTestEmail(e.target.value)}
            placeholder="your-email@example.com"
            className={`${inputCls} flex-1 min-w-[200px]`}
          />
          <button
            onClick={sendTestEmail}
            disabled={sendingTest || !testEmail.trim() || !subject.trim() || !body.trim()}
            className="btn-secondary px-4 py-2 text-sm shrink-0"
          >
            {sendingTest ? "Sending..." : "Send Test"}
          </button>
        </div>
        {testSendResult && (
          <p className={`text-sm mt-2 ${testSendResult.ok ? "text-green-500" : "text-red-500"}`}>
            {testSendResult.ok ? "✓ Test email sent — check your inbox." : `✗ ${testSendResult.error}`}
          </p>
        )}
      </div>

      {/* Send */}
      <div className="card p-5">
        <button
          onClick={sendCampaign}
          disabled={sending || recipients.length === 0 || !subject.trim() || !body.trim()}
          className="btn-primary px-6 py-3 text-sm flex items-center gap-2"
        >
          <Send size={16} /> {sending ? "Sending..." : `Send to ${recipients.length} Recipient${recipients.length === 1 ? "" : "s"}`}
        </button>

        {sendResult && (
          <div className="mt-4">
            <p className="text-sm font-semibold mb-2">
              {sendResult.successCount} / {sendResult.total} sent successfully
            </p>
            <div className="max-h-40 overflow-y-auto text-xs space-y-1">
              {sendResult.results.map((r, i) => (
                <div key={i} className={r.sent ? "text-green-500" : "text-red-500"}>
                  {r.sent ? "✓" : "✗"} {r.email} {r.error ? `— ${r.error}` : ""}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
