// @File: src/pages/admin/cms/CmsTenants.tsx
// @Desc: Business Tenants page. Lists business users (those who placed orders
//        or have admin/staff roles) and shows per-tenant aggregates — total
//        orders, lifetime revenue, last activity, status. Reuses the shared
//        `orders` entity and `admin_users` endpoint to build the view on the
//        fly (no new backend model required).
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Building2, Search, Download, Users, DollarSign, ShoppingCart } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import CmsLayout from "./CmsLayout";
import { PageHeader } from "./ui";
import LoadingSpinner from "@/components/LoadingSpinner";
import { listAdminUsers, type AdminUserRow } from "@/lib/adminApi";
import { toast } from "sonner";

const client = createClient();

interface OrderRow {
  id: number;
  user_id: string;
  order_number: string;
  status: string;
  payment_status: string | null;
  total: number | null;
  billing_email: string | null;
  created_at: string | null;
}

interface Tenant {
  user_id: string;
  email: string;
  name: string | null;
  role: string;
  is_active: boolean;
  total_orders: number;
  paid_orders: number;
  lifetime_revenue: number;
  last_order_at: string | null;
  created_at: string | null;
}

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  return iso.slice(0, 10);
}

function downloadCsv(rows: Tenant[]) {
  const header = [
    "user_id",
    "email",
    "name",
    "role",
    "active",
    "total_orders",
    "paid_orders",
    "lifetime_revenue_sar",
    "last_order_at",
    "created_at",
  ];
  const lines = [header.join(",")];
  for (const t of rows) {
    lines.push(
      [
        t.user_id,
        JSON.stringify(t.email ?? ""),
        JSON.stringify(t.name ?? ""),
        t.role,
        t.is_active ? "yes" : "no",
        t.total_orders,
        t.paid_orders,
        t.lifetime_revenue.toFixed(2),
        t.last_order_at ?? "",
        t.created_at ?? "",
      ].join(",")
    );
  }
  const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `tenants-${new Date().toISOString().slice(0, 10)}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

export default function CmsTenants() {
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [roleFilter, setRoleFilter] = useState<string>("all");

  const load = async () => {
    setLoading(true);
    try {
      // Pull admin-managed users and all orders in parallel.
      const [userList, ordersRes] = await Promise.all([
        listAdminUsers({ page: 1, page_size: 500 }),
        client.entities.orders.queryAll({
          query: {},
          sort: "-id",
          limit: 2000,
        }),
      ]);
      const users = userList.items as AdminUserRow[];
      const orders = ((ordersRes?.data?.items || []) as OrderRow[]) || [];

      // Aggregate orders by user_id.
      const byUser = new Map<
        string,
        { total: number; paid: number; revenue: number; last: string | null; email: string | null }
      >();
      for (const o of orders) {
        const uid = o.user_id || "anon";
        const entry = byUser.get(uid) || {
          total: 0,
          paid: 0,
          revenue: 0,
          last: null,
          email: o.billing_email,
        };
        entry.total += 1;
        if (o.payment_status === "paid" || o.status === "delivered" || o.status === "shipped") {
          entry.paid += 1;
          entry.revenue += Number(o.total || 0);
        }
        if (!entry.last || (o.created_at && o.created_at > entry.last)) {
          entry.last = o.created_at;
        }
        if (!entry.email && o.billing_email) entry.email = o.billing_email;
        byUser.set(uid, entry);
      }

      // Build tenant rows: every admin-user plus every user who appears in orders.
      const seen = new Set<string>();
      const rows: Tenant[] = [];
      for (const u of users) {
        const agg = byUser.get(u.id);
        rows.push({
          user_id: u.id,
          email: u.email,
          name: u.name,
          role: u.role,
          is_active: u.is_active,
          total_orders: agg?.total || 0,
          paid_orders: agg?.paid || 0,
          lifetime_revenue: agg?.revenue || 0,
          last_order_at: agg?.last ?? null,
          created_at: u.created_at,
        });
        seen.add(u.id);
      }
      for (const [uid, agg] of byUser.entries()) {
        if (seen.has(uid)) continue;
        rows.push({
          user_id: uid,
          email: agg.email || uid,
          name: null,
          role: "customer",
          is_active: true,
          total_orders: agg.total,
          paid_orders: agg.paid,
          lifetime_revenue: agg.revenue,
          last_order_at: agg.last,
          created_at: null,
        });
      }

      // Sort by lifetime revenue desc, then by total orders.
      rows.sort((a, b) => {
        if (b.lifetime_revenue !== a.lifetime_revenue) {
          return b.lifetime_revenue - a.lifetime_revenue;
        }
        return b.total_orders - a.total_orders;
      });
      setTenants(rows);
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Failed to load tenants.";
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const roles = useMemo(() => {
    const s = new Set<string>();
    tenants.forEach((t) => s.add(t.role));
    return Array.from(s).sort();
  }, [tenants]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return tenants.filter((t) => {
      if (roleFilter !== "all" && t.role !== roleFilter) return false;
      if (!q) return true;
      return (
        t.email.toLowerCase().includes(q) ||
        (t.name || "").toLowerCase().includes(q) ||
        t.user_id.toLowerCase().includes(q)
      );
    });
  }, [tenants, search, roleFilter]);

  const kpis = useMemo(() => {
    const totalTenants = tenants.length;
    const activeTenants = tenants.filter((t) => t.is_active).length;
    const totalRevenue = tenants.reduce((s, t) => s + t.lifetime_revenue, 0);
    const totalOrders = tenants.reduce((s, t) => s + t.total_orders, 0);
    return { totalTenants, activeTenants, totalRevenue, totalOrders };
  }, [tenants]);

  return (
    <CmsLayout>
      <PageHeader
        icon={<Building2 className="w-6 h-6" />}
        title="Business Tenants"
        description="All business accounts, their orders, lifetime revenue, and current status."
      />

      {/* KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
        <div className="bg-white border border-slate-200 rounded-2xl p-4">
          <div className="flex items-center gap-2 text-slate-500 text-xs uppercase font-bold tracking-wider">
            <Users className="w-4 h-4" /> Total Tenants
          </div>
          <div className="text-2xl font-extrabold text-slate-900 mt-1">{kpis.totalTenants}</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-2xl p-4">
          <div className="flex items-center gap-2 text-slate-500 text-xs uppercase font-bold tracking-wider">
            <Users className="w-4 h-4" /> Active
          </div>
          <div className="text-2xl font-extrabold text-emerald-600 mt-1">
            {kpis.activeTenants}
          </div>
        </div>
        <div className="bg-white border border-slate-200 rounded-2xl p-4">
          <div className="flex items-center gap-2 text-slate-500 text-xs uppercase font-bold tracking-wider">
            <ShoppingCart className="w-4 h-4" /> Orders
          </div>
          <div className="text-2xl font-extrabold text-slate-900 mt-1">{kpis.totalOrders}</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-2xl p-4">
          <div className="flex items-center gap-2 text-slate-500 text-xs uppercase font-bold tracking-wider">
            <DollarSign className="w-4 h-4" /> Lifetime Revenue
          </div>
          <div className="text-2xl font-extrabold text-[#0b6e3e] mt-1">
            SAR {kpis.totalRevenue.toFixed(2)}
          </div>
        </div>
      </div>

      {/* Controls */}
      <div className="mb-4 flex flex-col md:flex-row gap-3 md:items-center">
        <div className="relative max-w-md flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search email, name, id…"
            className="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg bg-white"
          />
        </div>
        <select
          value={roleFilter}
          onChange={(e) => setRoleFilter(e.target.value)}
          className="text-sm border border-slate-200 rounded-lg px-3 py-2 bg-white font-semibold"
        >
          <option value="all">All roles</option>
          {roles.map((r) => (
            <option key={r} value={r}>
              {r}
            </option>
          ))}
        </select>
        <button
          onClick={() => downloadCsv(filtered)}
          className="inline-flex items-center gap-2 text-sm font-semibold px-3 py-2 rounded-lg border border-slate-200 bg-white hover:bg-slate-50"
        >
          <Download className="w-4 h-4" /> Export CSV
        </button>
      </div>

      {loading ? (
        <div className="py-16 flex justify-center">
          <LoadingSpinner />
        </div>
      ) : filtered.length === 0 ? (
        <div className="bg-white border border-slate-200 rounded-2xl p-10 text-center text-slate-500">
          No tenants match your filters.
        </div>
      ) : (
        <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 text-slate-600 text-xs uppercase tracking-wider">
                <tr>
                  <th className="text-left px-4 py-3">Tenant</th>
                  <th className="text-left px-4 py-3">Role</th>
                  <th className="text-right px-4 py-3">Orders</th>
                  <th className="text-right px-4 py-3">Paid</th>
                  <th className="text-right px-4 py-3">Lifetime</th>
                  <th className="text-left px-4 py-3">Last Order</th>
                  <th className="text-left px-4 py-3">Status</th>
                  <th className="text-right px-4 py-3">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filtered.map((t) => (
                  <tr key={t.user_id} className="hover:bg-slate-50">
                    <td className="px-4 py-3">
                      <div className="font-semibold text-slate-900">
                        {t.name || t.email}
                      </div>
                      <div className="text-xs text-slate-500">{t.email}</div>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-[10px] uppercase font-bold px-2 py-0.5 rounded-full bg-slate-100 text-slate-700">
                        {t.role}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right font-semibold">{t.total_orders}</td>
                    <td className="px-4 py-3 text-right text-emerald-700 font-semibold">
                      {t.paid_orders}
                    </td>
                    <td className="px-4 py-3 text-right font-bold text-[#0b6e3e]">
                      SAR {t.lifetime_revenue.toFixed(2)}
                    </td>
                    <td className="px-4 py-3 text-slate-600">{fmtDate(t.last_order_at)}</td>
                    <td className="px-4 py-3">
                      {t.is_active ? (
                        <span className="text-[10px] uppercase font-bold px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700">
                          Active
                        </span>
                      ) : (
                        <span className="text-[10px] uppercase font-bold px-2 py-0.5 rounded-full bg-rose-100 text-rose-700">
                          Disabled
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <Link
                        to="/admin/cms/users"
                        className="text-xs font-semibold text-[#0b6e3e] hover:underline"
                      >
                        Manage →
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </CmsLayout>
  );
}