/**
 * app/earnings/page.tsx
 * Commission history and earnings overview page — professional theme.
 */

"use client";

import { useState, useEffect } from "react";
import axios from "axios";
import Link from "next/link";
import { useAuth } from "@/hooks/useAuth";
import { Badge } from "@/components/ui/Badge";
import { Loader2, TrendingUp, Wallet, History, ArrowRight, User as UserIcon } from "lucide-react";
import type { ICommission, IUser } from "@/types";

const statusVariant: Record<string, "success" | "warning" | "error" | "info"> = {
  paid: "success",
  processing: "info",
  pending: "warning",
  failed: "error",
};

export default function EarningsPage() {
  const { user } = useAuth();
  const [commissions, setCommissions] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [hasNext, setHasNext] = useState(false);

  useEffect(() => {
    if (!user) return;
    setLoading(true);
    axios.get(`/api/commissions?page=${page}&limit=20`)
      .then(({ data }) => {
        setCommissions(prev => page === 1 ? data.data : [...prev, ...data.data]);
        setTotal(data.total);
        setHasNext(data.hasNext);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [user, page]);

  return (
    <div className="space-y-10 md:space-y-12">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div>
          <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em] mb-2">Finance</p>
          <h1 className="text-3xl md:text-5xl font-jakarta font-black text-black tracking-tighter leading-none">
            Revenue Ledger.
          </h1>
          <p className="text-sm text-slate-500 mt-4 font-medium max-w-md">Your verified commission distributions across all Team levels.</p>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 md:grid-cols-3 gap-4 md:gap-6">
        {[
          { label: "Wallet Balance", value: `₹${(user?.wallet ?? 0).toLocaleString("en-IN")}`, icon: Wallet, dark: true },
          { label: "Total Earnings", value: `₹${(user?.totalEarnings ?? 0).toLocaleString("en-IN")}`, icon: TrendingUp, dark: false },
          { label: "Total Records", value: total.toString(), icon: History, dark: false },
        ].map(({ label, value, icon: Icon, dark }) => (
          <div key={label} className={`rounded-[1.5rem] p-6 flex flex-col justify-between min-h-[140px] ${dark ? "bg-black text-white shadow-2xl shadow-black/10" : "bg-white border border-slate-100 shadow-xl shadow-black/[0.02]"}`}>
            <div className="flex items-center justify-between">
              <p className={`text-[9px] font-black uppercase tracking-widest ${dark ? "text-slate-500" : "text-slate-300"}`}>{label}</p>
              <Icon className={`h-4 w-4 ${dark ? "text-slate-500" : "text-slate-200"}`} />
            </div>
            <p className={`text-xl md:text-2xl font-jakarta font-black tracking-tight ${dark ? "text-white" : "text-black"}`}>{value}</p>
          </div>
        ))}
      </div>

      {/* Commission Table */}
      <div className="rounded-[2rem] bg-white border border-slate-100 shadow-xl shadow-black/[0.02] overflow-hidden">
        <div className="px-8 py-6 border-b border-slate-100 flex items-center justify-between">
          <div className="flex items-center gap-3">
             <div className="h-8 w-8 rounded-xl bg-slate-50 border border-slate-100 flex items-center justify-center">
               <TrendingUp className="h-4 w-4 text-black" />
             </div>
             <h2 className="font-jakarta font-black text-sm text-black uppercase tracking-tight">Distribution History</h2>
          </div>
          <span className="text-[9px] font-black text-slate-300 uppercase tracking-widest">{total} TRANSACTIONS</span>
        </div>

        {loading && page === 1 ? (
          <div className="flex items-center justify-center py-24">
            <Loader2 className="h-10 w-10 text-black animate-spin opacity-20" />
          </div>
        ) : commissions.length === 0 ? (
          <div className="py-24 text-center">
            <div className="h-16 w-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-6">
               <History className="h-6 w-6 text-slate-200" />
            </div>
            <p className="font-jakarta font-black text-black uppercase tracking-tight mb-2">No activity detected.</p>
            <p className="text-xs text-slate-400 font-medium tracking-tight">Earnings will appear here as your network scales.</p>
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-slate-50/50">
                    <th className="text-left px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Date</th>
                    <th className="text-left px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Source</th>
                    <th className="text-left px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Property Asset</th>
                    <th className="text-left px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Yield</th>
                    <th className="text-right px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Revenue</th>
                    <th className="text-right px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {commissions.map((c) => (
                    <tr key={c._id} className="hover:bg-slate-50/50 transition-colors group">
                      <td className="px-8 py-5 text-xs font-bold text-slate-400 whitespace-nowrap">
                        {new Date(c.createdAt).toLocaleDateString("en-IN", { day: '2-digit', month: 'short', year: 'numeric' }).toUpperCase()}
                      </td>
                      <td className="px-8 py-5">
                        <div className="flex items-center gap-3">
                          <span className="flex-shrink-0 inline-flex items-center justify-center h-6 w-6 rounded bg-black text-white text-[9px] font-black tracking-widest">
                            L{c.level}
                          </span>
                          <div className="min-w-0">
                            <p className="text-xs font-black text-black truncate uppercase tracking-tight">
                              {c.fromUser?.name || "Direct Sale"}
                            </p>
                            <p className="text-[9px] text-slate-400 font-bold tracking-widest uppercase">
                              {c.fromUser?.referralCode || "OWN"}
                            </p>
                          </div>
                        </div>
                      </td>
                      <td className="px-8 py-5 text-xs font-black text-black truncate max-w-[200px] uppercase tracking-tight">
                        {(c.property as any)?.title || "Property Asset"}
                      </td>
                      <td className="px-8 py-5 text-xs font-bold text-slate-400">{c.percentage}%</td>
                      <td className="px-8 py-5 text-right font-jakarta font-black text-sm text-black">
                        ₹{c.amount.toLocaleString("en-IN")}
                      </td>
                      <td className="px-8 py-5 text-right">
                        <Badge variant={statusVariant[c.status] ?? "default"} className="uppercase text-[9px] font-black tracking-widest">
                          {c.status}
                        </Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {hasNext && (
              <div className="px-8 py-6 bg-slate-50/50 text-center">
                <button
                  id="load-more-commissions"
                  onClick={() => setPage(p => p + 1)}
                  disabled={loading}
                  className="text-[10px] font-black text-black uppercase tracking-[0.2em] hover:opacity-50 transition-all disabled:opacity-30 flex items-center gap-2 mx-auto"
                >
                  {loading ? "Synchronizing..." : "View Older Distributions"}
                  <ArrowRight className="h-3 w-3" />
                </button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
