/**
 * app/admin/page.tsx
 * Admin overview dashboard — key stats cards + recent sales table.
 *
 * ADMIN MODULE — self-contained, no changes to agent dashboard or other pages.
 */

"use client";

import { useEffect, useState } from "react";
import { Users, TrendingUp, ShoppingBag, Percent, ArrowRight } from "lucide-react";
import Link from "next/link";
import toast from "react-hot-toast";

interface Stats {
  totalAgents: number;
  activeAgents: number;
  inactiveAgents: number;
  totalSalesValue: number;
  totalSalesCount: number;
  totalCommissionsPaid: number;
  recentSales: Array<{
    _id: string;
    agentId: { name: string; email: string } | null;
    propertyTitle: string;
    saleAmount: number;
    createdAt: string;
  }>;
}

function StatCard({
  icon: Icon,
  label,
  value,
  sub,
  dark,
}: {
  icon: React.ElementType;
  label: string;
  value: string;
  sub?: string;
  dark?: boolean;
}) {
  return (
    <div
      className={`rounded-2xl p-6 flex flex-col gap-4 transition-all duration-300 ${
        dark
          ? "bg-slate-900 text-white shadow-xl shadow-indigo-500/10"
          : "bg-white text-slate-900 border border-slate-100 shadow-sm"
      }`}
    >
      <div
        className={`h-10 w-10 rounded-xl flex items-center justify-center transition-colors ${
          dark ? "bg-white/10" : "bg-slate-50 border border-slate-100"
        }`}
      >
        <Icon className={`h-5 w-5 ${dark ? "text-indigo-400" : "text-indigo-600"}`} />
      </div>
      <div>
        <p
          className={`text-[10px] font-black uppercase tracking-widest mb-1 ${
            dark ? "text-slate-400" : "text-slate-400"
          }`}
        >
          {label}
        </p>
        <p className={`text-3xl font-black tracking-tight ${dark ? "text-white" : "text-slate-900"}`}>
          {value}
        </p>
        {sub && (
          <p
            className={`text-xs mt-1 font-medium ${
              dark ? "text-slate-500" : "text-slate-400"
            }`}
          >
            {sub}
          </p>
        )}
      </div>
    </div>
  );
}

export default function AdminOverviewPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/stats")
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setStats(d.data);
        else toast.error(d.error ?? "Failed to load stats");
      })
      .catch(() => toast.error("Server error loading stats"))
      .finally(() => setLoading(false));
  }, []);

  const fmt = (n: number) =>
    `₹${n.toLocaleString("en-IN", { maximumFractionDigits: 2 })}`;

  return (
    <div className="space-y-8">
      {/* Header */}
      <div>
        <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em] mb-1">
          Admin Panel
        </p>
        <h1 className="text-3xl font-black text-slate-900 tracking-tight">Overview</h1>
      </div>

      {/* Stats */}
      {loading ? (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="h-36 rounded-2xl bg-slate-100 animate-pulse" />
          ))}
        </div>
      ) : stats ? (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard dark icon={Users} label="Total Associates" value={String(stats.totalAgents)}
            sub={`${stats.activeAgents} active · ${stats.inactiveAgents} inactive`} />
          <StatCard icon={ShoppingBag} label="Total Sales" value={String(stats.totalSalesCount)}
            sub={fmt(stats.totalSalesValue) + " value"} />
          <StatCard icon={TrendingUp} label="Total Sales Value" value={fmt(stats.totalSalesValue)} />
          <StatCard icon={Percent} label="Commissions Paid" value={fmt(stats.totalCommissionsPaid)} />
        </div>
      ) : null}

      {/* Quick Links */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {[
          { href: "/admin/agents", label: "Manage Associates", desc: "View all associates, enable or disable access.", icon: Users },
          { href: "/admin/sales", label: "Record a Sale", desc: "Add a sale to auto-distribute commissions.", icon: ShoppingBag },
          { href: "/admin/commission-config", label: "Commission Rates", desc: "Set per-level split percentages.", icon: Percent },
        ].map(({ href, label, desc, icon: Icon }) => (
          <Link
            key={href}
            href={href}
            className="group rounded-2xl bg-white border border-slate-100 p-6 flex flex-col gap-4 hover:-translate-y-1 transition-all duration-200 hover:shadow-lg hover:shadow-indigo-500/5"
          >
            <div className="h-10 w-10 rounded-xl bg-slate-50 border border-slate-100 flex items-center justify-center transition-colors group-hover:bg-indigo-600">
              <Icon className="h-5 w-5 text-slate-900 group-hover:text-white" />
            </div>
            <div className="flex-1">
              <p className="font-black text-slate-900 text-sm mb-1">{label}</p>
              <p className="text-xs text-slate-500 font-medium">{desc}</p>
            </div>
            <ArrowRight className="h-4 w-4 text-slate-300 group-hover:text-indigo-600 transition-colors" />
          </Link>
        ))}
      </div>

      {/* Recent Sales */}
      {stats && stats.recentSales.length > 0 && (
        <div className="bg-white rounded-2xl border border-slate-100 overflow-hidden shadow-sm">
          <div className="px-6 py-5 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
            <h2 className="font-black text-slate-900 text-[10px] uppercase tracking-[0.2em]">Recent Sales</h2>
            <Link href="/admin/sales" className="text-[10px] font-black text-indigo-600 hover:text-indigo-700 transition-colors uppercase tracking-widest">
              View all →
            </Link>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-slate-50">
                  <th className="text-left px-6 py-3 text-[10px] font-black uppercase tracking-widest text-slate-400">Agent</th>
                  <th className="text-left px-6 py-3 text-[10px] font-black uppercase tracking-widest text-slate-400">Property</th>
                  <th className="text-right px-6 py-3 text-[10px] font-black uppercase tracking-widest text-slate-400">Amount</th>
                  <th className="text-right px-6 py-3 text-[10px] font-black uppercase tracking-widest text-slate-400">Date</th>
                </tr>
              </thead>
              <tbody>
                {stats.recentSales.map((s) => (
                  <tr key={s._id} className="border-b border-slate-50 last:border-0 hover:bg-indigo-50/30 transition-colors group">
                    <td className="px-6 py-4 font-black text-slate-900 text-xs uppercase tracking-tight">{s.agentId?.name ?? "—"}</td>
                    <td className="px-6 py-4 text-slate-500 text-xs font-medium max-w-[200px] truncate">{s.propertyTitle}</td>
                    <td className="px-6 py-4 text-right font-black text-slate-900">{fmt(s.saleAmount)}</td>
                    <td className="px-6 py-4 text-right text-slate-400 text-xs">
                      {new Date(s.createdAt).toLocaleDateString("en-IN")}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
