/**
 * app/admin/payouts/page.tsx
 * Admin Payout Management — Controlled exclusively by administrators.
 * View agent balances, initiate payments, and track settlement history.
 */

"use client";

import { useState, useEffect } from "react";
import axios from "axios";
import { Badge } from "@/components/ui/Badge";
import { 
  Wallet, 
  Search, 
  CheckCircle2, 
  User as UserIcon,
  Calendar,
  ArrowUpRight,
  History,
  TrendingUp,
  Loader2,
  AlertCircle
} from "lucide-react";
import toast from "react-hot-toast";

export default function AdminPayoutsPage() {
  const [tab, setTab] = useState<"payable" | "history">("payable");
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState<string | null>(null);
  
  const [agents, setAgents] = useState<any[]>([]);
  const [history, setHistory] = useState<any[]>([]);
  const [metrics, setMetrics] = useState({ totalPayable: 0, totalSettled: 0 });

  const fetchData = async () => {
    try {
      setLoading(true);
      const res = await axios.get("/api/admin/payouts");
      if (res.data.success) {
        setAgents(res.data.data.agents);
        setHistory(res.data.data.history);
        setMetrics(res.data.data.metrics);
      }
    } catch (err: any) {
      toast.error(err.response?.data?.error || "Failed to fetch payout data");
    } finally {
      setLoading(false);
    }
  };

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

  const handlePay = async (agent: any) => {
    const method = window.prompt(`Enter payment method for ${agent.name} (e.g. Bank Transfer, UPI):`, "Bank Transfer");
    if (!method) return;

    const ref = window.prompt(`Enter reference ID or transaction hash (optional):`, "");
    
    try {
      setSubmitting(agent._id);
      const res = await axios.post("/api/admin/payouts", {
        agentId: agent._id,
        amount: agent.wallet,
        method: method,
        referenceId: ref
      });

      if (res.data.success) {
        toast.success(`Settlement of ₹${agent.wallet.toLocaleString()} completed for ${agent.name}`);
        fetchData(); // Refresh all data
      }
    } catch (err: any) {
      toast.error(err.response?.data?.error || "Payment failed");
    } finally {
      setSubmitting(null);
    }
  };

  const filteredAgents = agents.filter(a => 
    a.name.toLowerCase().includes(search.toLowerCase()) || 
    a.email.toLowerCase().includes(search.toLowerCase()) ||
    a.referralCode.toLowerCase().includes(search.toLowerCase())
  );

  const filteredHistory = history.filter(h => 
    h.user?.name.toLowerCase().includes(search.toLowerCase()) ||
    h.id?.toLowerCase().includes(search.toLowerCase())
  );

  if (loading) {
    return (
      <div className="min-h-[60vh] flex flex-col items-center justify-center space-y-4">
        <Loader2 className="h-10 w-10 animate-spin text-black" />
        <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">Loading Financial Data...</p>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <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">Administrative</p>
          <h1 className="text-3xl md:text-5xl font-jakarta font-black text-black tracking-tighter leading-none">
            Payout Management.
          </h1>
          <p className="text-sm text-slate-500 mt-4 font-medium max-w-md">Exclusively manage Associate settlements and revenue distribution.</p>
        </div>
      </div>

      {/* Stats Summary */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-black p-8 rounded-[2rem] text-white shadow-2xl shadow-black/10 relative overflow-hidden">
          <div className="relative z-10">
            <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-4">Total Payable Balance</p>
            <p className="text-4xl font-jakarta font-black tracking-tight mb-2">₹{metrics.totalPayable.toLocaleString("en-IN")}</p>
            <div className="flex items-center gap-2 mt-4">
              <span className="h-1.5 w-1.5 rounded-full bg-amber-500 animate-pulse" />
              <p className="text-[9px] text-slate-400 font-bold uppercase tracking-widest">Pending Disbursal</p>
            </div>
          </div>
          <div className="absolute -right-10 -bottom-10 h-40 w-40 bg-indigo-600/20 rounded-full blur-3xl" />
        </div>

        <div className="bg-white p-8 rounded-[2rem] border border-slate-100 shadow-xl shadow-black/[0.02]">
          <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4">Total Settled (All Time)</p>
          <div className="flex items-center justify-between">
            <p className="text-4xl font-jakarta font-black text-black tracking-tight">₹{metrics.totalSettled.toLocaleString("en-IN")}</p>
            <div className="h-12 w-12 rounded-2xl bg-emerald-50 flex items-center justify-center">
              <TrendingUp className="h-6 w-6 text-emerald-500" />
            </div>
          </div>
        </div>

        <div className="bg-white p-8 rounded-[2rem] border border-slate-100 shadow-xl shadow-black/[0.02]">
          <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4">Eligible Associates </p>
          <div className="flex items-center justify-between">
            <p className="text-4xl font-jakarta font-black text-black tracking-tight">{agents.length}</p>
            <div className="h-12 w-12 rounded-2xl bg-indigo-50 flex items-center justify-center">
              <UserIcon className="h-6 w-6 text-indigo-500" />
            </div>
          </div>
        </div>
      </div>

      {/* Main Panel */}
      <div className="bg-white rounded-[2.5rem] border border-slate-100 shadow-xl shadow-black/[0.02] overflow-hidden">
        {/* Tabs & Search */}
        <div className="px-10 py-8 border-b border-slate-100 flex flex-col lg:flex-row lg:items-center justify-between gap-6">
          <div className="flex p-1.5 bg-slate-50 rounded-2xl w-fit">
            <button 
              onClick={() => setTab("payable")}
              className={`px-6 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${tab === "payable" ? "bg-white text-black shadow-sm" : "text-slate-400 hover:text-black"}`}
            >
              Payable Associates
            </button>
            <button 
              onClick={() => setTab("history")}
              className={`px-6 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${tab === "history" ? "bg-white text-black shadow-sm" : "text-slate-400 hover:text-black"}`}
            >
              Settlement History
            </button>
          </div>

          <div className="relative group">
            <Search className="h-4 w-4 absolute left-5 top-1/2 -translate-y-1/2 text-slate-300 group-focus-within:text-black transition-colors" />
            <input 
              type="text" 
              placeholder="Search agent or ID..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-12 pr-6 py-4 rounded-2xl border border-slate-100 bg-slate-50 text-[10px] font-black uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-black/5 w-full lg:w-80 transition-all"
            />
          </div>
        </div>

        {/* Content */}
        {tab === "payable" ? (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-slate-50/50">
                  <th className="text-left px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Associate Profile</th>
                  <th className="text-left px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Performance</th>
                  <th className="text-right px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Current Balance</th>
                  <th className="text-right px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Action</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {filteredAgents.map((a) => (
                  <tr key={a._id} className="hover:bg-slate-50/30 transition-colors group">
                    <td className="px-10 py-8">
                      <div className="flex items-center gap-4">
                        <div className="h-12 w-12 rounded-2xl bg-slate-100 flex items-center justify-center text-slate-400 font-black text-xs">
                          {a.name[0]}
                        </div>
                        <div>
                          <p className="text-xs font-black text-black uppercase tracking-tight">{a.name}</p>
                          <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest">{a.referralCode} • {a.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-10 py-8">
                      <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1">Total Earned: ₹{a.totalEarnings.toLocaleString()}</p>
                      <p className="text-[9px] text-slate-300 font-bold uppercase">Updated: {new Date(a.updatedAt).toLocaleDateString()}</p>
                    </td>
                    <td className="px-10 py-8 text-right">
                      <p className="font-jakarta font-black text-lg text-black tracking-tight">₹{a.wallet.toLocaleString()}</p>
                    </td>
                    <td className="px-10 py-8 text-right">
                      <button 
                        onClick={() => handlePay(a)}
                        disabled={submitting === a._id}
                        className="px-6 py-3 rounded-xl bg-black text-white text-[10px] font-black uppercase tracking-widest hover:bg-slate-800 transition-all shadow-xl shadow-black/10 active:scale-95 flex items-center gap-2 ml-auto disabled:opacity-50"
                      >
                        {submitting === a._id ? (
                          <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        ) : (
                          <>Initiate Payment <ArrowUpRight className="h-3.5 w-3.5" /></>
                        )}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {filteredAgents.length === 0 && (
              <div className="py-32 text-center">
                <div className="h-20 w-20 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-6 border border-slate-100">
                   <CheckCircle2 className="h-8 w-8 text-emerald-500" />
                </div>
                <p className="font-jakarta font-black text-black uppercase tracking-tight mb-2">No payable associates.</p>
                <p className="text-xs text-slate-400 font-medium tracking-tight">All verified balances are currently settled.</p>
              </div>
            )}
          </div>
        ) : (
          <div className="overflow-x-auto">
             <table className="w-full">
              <thead>
                <tr className="bg-slate-50/50">
                  <th className="text-left px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Associate</th>
                  <th className="text-left px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Settled On</th>
                  <th className="text-left px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Method</th>
                  <th className="text-right px-10 py-5 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">Amount</th>
                  <th className="text-right px-10 py-5 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">
                {filteredHistory.map((h) => (
                  <tr key={h._id} className="hover:bg-slate-50/30 transition-colors">
                    <td className="px-10 py-8">
                      <p className="text-xs font-black text-black uppercase tracking-tight">{h.user?.name}</p>
                      <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest">{h.user?.referralCode}</p>
                    </td>
                    <td className="px-10 py-8 text-[10px] text-slate-400 font-bold uppercase tracking-widest">
                       {new Date(h.processedAt).toLocaleDateString("en-IN", { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }).toUpperCase()}
                    </td>
                    <td className="px-10 py-8 text-[10px] font-black text-slate-500 uppercase tracking-widest">
                       {h.method} {h.referenceId && `• ${h.referenceId}`}
                    </td>
                    <td className="px-10 py-8 text-right font-jakarta font-black text-base text-black tracking-tight">₹{h.amount.toLocaleString()}</td>
                    <td className="px-10 py-8 text-right">
                       <Badge variant="success" className="uppercase text-[9px] font-black tracking-widest">SETTLED</Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {filteredHistory.length === 0 && (
              <div className="py-32 text-center">
                <div className="h-20 w-20 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-6 border border-slate-100">
                   <History className="h-8 w-8 text-slate-200" />
                </div>
                <p className="font-jakarta font-black text-black uppercase tracking-tight mb-2">No history found.</p>
                <p className="text-xs text-slate-400 font-medium tracking-tight">Settlement records will appear here after processing.</p>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
