import { prisma } from "@/lib/prisma";
import { formatPaise, formatDate } from "@/lib/format";
import MarketingTabs from "@/components/admin/MarketingTabs";
import ScrollableTable from "@/components/admin/ScrollableTable";

const ABANDONED_AFTER_MS = 60 * 60 * 1000; // 1 hour

function customerWhatsappLink(phone: string, message: string) {
  const digits = phone.replace(/\D/g, "");
  const withCountryCode = digits.length === 10 ? `91${digits}` : digits;
  return `https://wa.me/${withCountryCode}?text=${encodeURIComponent(message)}`;
}

export default async function AdminAbandonedCartPage() {
  const cutoff = new Date(Date.now() - ABANDONED_AFTER_MS);
  const orders = await prisma.order.findMany({
    where: { status: "pending", createdAt: { lt: cutoff } },
    include: { items: true },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Abandoned Cart</h1>
      <p className="mt-1 text-sm text-stone-500">
        The cart itself is never seen by the server (it&apos;s stored only in the customer&apos;s browser), so this can&apos;t
        catch someone who added items and left before reaching checkout. What it does catch, honestly: checkouts that were{" "}
        <strong>started</strong> (name, address, and contact info were filled in) but never paid, over an hour ago —
        the most actionable kind, since you already have their details.
      </p>

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

      {orders.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No abandoned checkouts right now.</p>
      ) : (
        <ScrollableTable>
          <table className="w-full min-w-[900px] text-sm">
            <thead className="sticky top-0 z-10 bg-rose-50 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Customer</th>
                <th className="p-3">Items</th>
                <th className="p-3">Total</th>
                <th className="p-3">Started</th>
                <th className="p-3">Follow up</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {orders.map((o) => (
                <tr key={o.id}>
                  <td className="whitespace-nowrap p-3">
                    <p className="font-medium text-stone-800">{o.customerName}</p>
                    <p className="text-xs text-stone-500">{o.email} · {o.phone}</p>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{o.items.length} item{o.items.length !== 1 ? "s" : ""}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{formatPaise(o.total)}</td>
                  <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(o.createdAt)}</td>
                  <td className="whitespace-nowrap p-3">
                    <a
                      href={customerWhatsappLink(o.phone, `Hi ${o.customerName}! We noticed you didn't finish your order (${o.orderNumber}) at Iniyaval Return Gifts — anything we can help with?`)}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-xs font-medium text-emerald-700 hover:underline"
                    >
                      WhatsApp them →
                    </a>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      )}
    </div>
  );
}
