import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { sendEmailCampaign } from "@/lib/actions/marketing";
import MarketingTabs from "@/components/admin/MarketingTabs";

export default async function AdminCampaignsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const [groups, campaigns, customerCount] = await Promise.all([
    prisma.customerGroup.findMany({ orderBy: { name: "asc" } }),
    prisma.emailCampaign.findMany({ orderBy: { createdAt: "desc" }, take: 20 }),
    prisma.customer.count({ where: { blocked: false } }),
  ]);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Email / WhatsApp Campaigns</h1>
      <p className="mt-1 text-sm text-stone-500">
        Email campaigns send for real, through your Resend account. WhatsApp bulk campaigns aren&apos;t wired up — that
        needs a paid WhatsApp Business API integration (Meta approval, message templates, per-message cost), which isn&apos;t
        set up here. One-to-one WhatsApp chat links still work everywhere else in the site.
      </p>

      <MarketingTabs active="/iv-manage-84x2/marketing/campaigns" />

      {error && <p className="mb-4 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <form action={sendEmailCampaign} className="grid max-w-2xl grid-cols-1 gap-3 rounded-lg border border-rose-100 bg-white p-4">
        <select name="audience" className="rounded-md border border-stone-300 px-2 py-2 text-sm">
          <option value="all">All customers ({customerCount})</option>
          {groups.map((g) => (
            <option key={g.id} value={g.id}>
              Group: {g.name}
            </option>
          ))}
          <option value="manual">Manual list (paste emails)</option>
        </select>
        <textarea
          name="manualEmails"
          rows={2}
          placeholder="Only used if audience is 'Manual list' — one email per line or comma-separated"
          className="rounded-md border border-stone-300 px-2 py-2 text-sm"
        />
        <input name="subject" required placeholder="Subject" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <textarea name="body" required rows={6} placeholder="Message" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
          Send now
        </button>
      </form>

      <h2 className="mt-8 text-sm font-semibold text-stone-700">Sent campaigns</h2>
      <div className="mt-3 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {campaigns.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No campaigns sent yet.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Subject</th>
                <th className="p-3">Audience</th>
                <th className="p-3">Sent to</th>
                <th className="p-3">Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {campaigns.map((c) => (
                <tr key={c.id}>
                  <td className="p-3 font-medium text-stone-800">{c.subject}</td>
                  <td className="p-3 text-stone-600">{c.audience === "all" ? "All customers" : c.audience === "manual" ? "Manual list" : "Group"}</td>
                  <td className="p-3 text-stone-600">{c.sentCount}</td>
                  <td className="p-3 text-stone-500">{c.sentAt ? formatDate(c.sentAt) : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
