"use client";

import Link from "next/link";
import { Badge } from "@/components/ui/kit";
import { SubscriptionBadge } from "@/components/billing/plan-badge";
import { formatDate, formatPaise } from "@/lib/format";
import type { CustomerRow } from "@/lib/types";

/** Customer list used by the admin and reseller portals. */
export function CustomerTable({ rows, hrefFor, showReseller }: { rows: CustomerRow[]; hrefFor: (c: CustomerRow) => string; showReseller?: boolean }) {
  return (
    <div className="relative overflow-x-auto">
      <table className="w-full min-w-[760px] text-sm">
        <thead className="border-b border-line text-left text-[13px] text-muted">
          <tr>
            <th className="px-5 py-3 font-medium">Customer</th>
            {showReseller && <th className="px-3 py-3 font-medium">Reseller</th>}
            <th className="px-3 py-3 font-medium">Plan</th>
            <th className="px-3 py-3 text-right font-medium">Wallet</th>
            <th className="px-3 py-3 font-medium">Last payment</th>
            <th className="px-5 py-3 font-medium">Account</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-line">
          {rows.map((c) => (
            <tr key={c.id} className="group relative hover:bg-paper/60">
              <td className="px-5 py-3">
                <Link href={hrefFor(c)} className="font-medium text-ink after:absolute after:inset-0 group-hover:text-teal">
                  {c.name}
                </Link>
                <p className="text-[13px] text-muted">{c.owner ? `${c.owner.name}, ${c.owner.email}` : "No owner"}</p>
              </td>
              {showReseller && <td className="px-3 py-3 text-muted">{c.reseller_name ?? "Direct"}</td>}
              <td className="px-3 py-3">
                {c.subscription ? (
                  <span className="flex flex-wrap items-center gap-2">
                    {c.subscription.plan.name} <SubscriptionBadge status={c.subscription.status} />
                  </span>
                ) : (
                  <span className="text-muted">Not billed</span>
                )}
              </td>
              <td className="tabular px-3 py-3 text-right">{formatPaise(c.wallet_paise)}</td>
              <td className="px-3 py-3 text-muted">{c.last_payment ? `${formatPaise(c.last_payment.total_paise)}, ${formatDate(c.last_payment.at)}` : "—"}</td>
              <td className="px-5 py-3">
                <Badge tone={c.status === "active" ? "teal" : "brick"}>{c.status === "active" ? "Active" : "Suspended"}</Badge>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
