"use client";

import { useEffect, useState } from "react";

type TreasuryStats = {
  available?: {
    usdc?: number;
    fiat?: number;
  };
  revenue?: {
    usdc?: number;
    fiat?: number;
  };
  gmv?: {
    usdc?: number;
    fiat?: number;
  };
  recent_transactions?: Array<{
    type: string;
    source: string;
    amount: number;
    date: string;
  }>;
};

export default function TreasuryDashboard() {
  const [stats, setStats] = useState<TreasuryStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState("");
  const [withdrawing, setWithdrawing] = useState(false);
  const [withdrawType, setWithdrawType] = useState<"CRYPTO" | "FIAT">("CRYPTO");
  const [destination, setDestination] = useState("");
  const [message, setMessage] = useState("");
  const cents = (value: number | undefined) => value ?? 0;

  useEffect(() => {
    const loadStats = async () => {
      try {
        const res = await fetch("/api/admin/treasury/stats");
        const data = await res.json().catch(() => ({}));
        if (!res.ok) {
          throw new Error(data.error || `Treasury stats request failed (${res.status})`);
        }
        setStats(data);
      } catch (error) {
        setLoadError(error instanceof Error ? error.message : "Unable to load treasury stats.");
      } finally {
        setLoading(false);
      }
    };
    void loadStats();
  }, []);

  const handleWithdraw = async () => {
    if (!stats) {
      setMessage("⚠️ Treasury stats are unavailable.");
      return;
    }
    if (!destination) {
      setMessage("⚠️ Please enter a destination address or bank ID.");
      return;
    }
    
    const amount = withdrawType === "CRYPTO" ? cents(stats.available?.usdc) : cents(stats.available?.fiat);
    if (amount <= 0) {
      setMessage("⚠️ No balance available to withdraw.");
      return;
    }

    setWithdrawing(true);
    setMessage("");

    try {
      const res = await fetch("/api/admin/withdraw", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ destination, type: withdrawType, amount })
      });
      const data = await res.json();
      
      if (data.success) {
        setMessage(`✅ ${data.message}`);
        // Refresh stats
        const updatedStatsRes = await fetch("/api/admin/treasury/stats");
        const updatedStats = await updatedStatsRes.json().catch(() => ({}));
        if (!updatedStatsRes.ok) {
          throw new Error(updatedStats.error || "Unable to refresh treasury stats.");
        }
        setStats(updatedStats);
      } else {
        setMessage(`❌ Error: ${data.error}`);
      }
    } catch (error) {
      setMessage(`❌ ${error instanceof Error ? error.message : "Network Error."}`);
    } finally {
      setWithdrawing(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-[#0a0a0a] text-white flex items-center justify-center">
        <div className="animate-pulse flex flex-col items-center">
          <div className="w-16 h-16 rounded-full border-t-2 border-r-2 border-purple-500 animate-spin"></div>
          <p className="mt-4 text-purple-400 font-mono">Syncing Treasury Data...</p>
        </div>
      </div>
    );
  }

  if (loadError || !stats) {
    return (
      <div className="min-h-screen bg-[#0a0a0a] text-white flex items-center justify-center p-8">
        <div className="max-w-md rounded-2xl border border-red-500/30 bg-red-950/20 p-6 text-center">
          <h1 className="text-xl font-semibold text-red-200">Treasury Unavailable</h1>
          <p className="mt-3 text-sm text-red-100/80">{loadError || "Treasury stats are unavailable."}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#050505] text-gray-200 p-8 font-sans relative overflow-hidden">
      {/* Background glow effects */}
      <div className="absolute top-[-20%] left-[-10%] w-[50%] h-[50%] bg-purple-900/30 blur-[150px] rounded-full pointer-events-none"></div>
      <div className="absolute bottom-[-20%] right-[-10%] w-[50%] h-[50%] bg-blue-900/30 blur-[150px] rounded-full pointer-events-none"></div>

      <div className="max-w-6xl mx-auto relative z-10">
        <header className="mb-12 flex justify-between items-end border-b border-white/10 pb-6">
          <div>
            <h1 className="text-4xl font-extrabold bg-gradient-to-r from-purple-400 to-blue-500 bg-clip-text text-transparent">
              Platform Treasury
            </h1>
            <p className="text-gray-400 mt-2 font-mono text-sm">VibeWork Global Master Account</p>
          </div>
          <div className="text-right">
            <p className="text-xs text-gray-500 uppercase tracking-widest">Network Status</p>
            <div className="flex items-center gap-2 justify-end mt-1">
              <span className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span>
              <span className="text-sm font-mono text-green-400">All Systems Nominal</span>
            </div>
          </div>
        </header>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
          {/* Crypto Treasury */}
          <div className="bg-white/5 border border-white/10 rounded-2xl p-8 backdrop-blur-xl hover:bg-white/10 transition-colors group relative overflow-hidden">
            <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
              <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"></path><path d="M12 18V6"></path></svg>
            </div>
            <h2 className="text-lg text-gray-400 font-semibold mb-2">USDC Reserve (Crypto)</h2>
            <div className="text-5xl font-bold text-white font-mono mb-4">
              ${((stats.available?.usdc || 0) / 100).toLocaleString(undefined, {minimumFractionDigits: 2})}
            </div>
            <div className="flex justify-between text-sm text-gray-500 border-t border-white/10 pt-4">
              <span>Lifetime Revenue: ${(cents(stats.revenue?.usdc) / 100).toLocaleString()}</span>
              <span>Total GMV: ${(cents(stats.gmv?.usdc) / 100).toLocaleString()}</span>
            </div>
          </div>

          {/* Fiat Treasury */}
          <div className="bg-white/5 border border-white/10 rounded-2xl p-8 backdrop-blur-xl hover:bg-white/10 transition-colors group relative overflow-hidden">
             <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
              <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"></rect><line x1="2" y1="10" x2="22" y2="10"></line></svg>
            </div>
            <h2 className="text-lg text-gray-400 font-semibold mb-2">Stripe Balance (Fiat)</h2>
            <div className="text-5xl font-bold text-white font-mono mb-4">
              ${((stats.available?.fiat || 0) / 100).toLocaleString(undefined, {minimumFractionDigits: 2})}
            </div>
            <div className="flex justify-between text-sm text-gray-500 border-t border-white/10 pt-4">
              <span>Lifetime Revenue: ${(cents(stats.revenue?.fiat) / 100).toLocaleString()}</span>
              <span>Total GMV: ${(cents(stats.gmv?.fiat) / 100).toLocaleString()}</span>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          
          {/* Withdrawal Panel */}
          <div className="lg:col-span-2 bg-[#111] border border-[#333] rounded-2xl p-8">
            <h2 className="text-2xl font-semibold mb-6 flex items-center gap-3">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 17l5-5-5-5"></path><path d="M3 12h18"></path></svg>
              Execute Withdrawal
            </h2>

            <div className="flex gap-4 mb-6">
              <button 
                onClick={() => setWithdrawType("CRYPTO")}
                className={`flex-1 py-3 px-4 rounded-xl font-medium transition-all ${withdrawType === "CRYPTO" ? 'bg-purple-600 text-white shadow-[0_0_20px_rgba(147,51,234,0.4)]' : 'bg-[#222] text-gray-400 hover:bg-[#333]'}`}
              >
                USDC (Crypto)
              </button>
              <button 
                onClick={() => setWithdrawType("FIAT")}
                className={`flex-1 py-3 px-4 rounded-xl font-medium transition-all ${withdrawType === "FIAT" ? 'bg-blue-600 text-white shadow-[0_0_20px_rgba(37,99,235,0.4)]' : 'bg-[#222] text-gray-400 hover:bg-[#333]'}`}
              >
                USD (Stripe)
              </button>
            </div>

            <div className="mb-6">
              <label className="block text-sm text-gray-400 mb-2">
                {withdrawType === "CRYPTO" ? "Cold Wallet Address (ERC-20)" : "Stripe Connect Bank Account ID"}
              </label>
              <input 
                type="text" 
                value={destination}
                onChange={(e) => setDestination(e.target.value)}
                placeholder={withdrawType === "CRYPTO" ? "0x..." : "acct_1Ou..."}
                className="w-full bg-[#0a0a0a] border border-[#333] rounded-xl px-4 py-3 text-white font-mono focus:outline-none focus:border-purple-500 transition-colors"
              />
            </div>

            <div className="mb-6 bg-[#0a0a0a] p-4 rounded-xl border border-white/5 flex justify-between items-center">
              <span className="text-gray-400">Amount to Withdraw</span>
              <span className="text-xl font-mono text-white">
                ${(cents(withdrawType === "CRYPTO" ? stats.available?.usdc : stats.available?.fiat) / 100).toLocaleString(undefined, {minimumFractionDigits: 2})}
              </span>
            </div>

            <button 
              onClick={handleWithdraw}
              disabled={withdrawing || cents(withdrawType === "CRYPTO" ? stats.available?.usdc : stats.available?.fiat) <= 0}
              className="w-full py-4 rounded-xl font-bold text-lg bg-gradient-to-r from-purple-500 to-blue-600 hover:from-purple-400 hover:to-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-[0_0_30px_rgba(147,51,234,0.3)] hover:shadow-[0_0_40px_rgba(147,51,234,0.5)] transform hover:-translate-y-1"
            >
              {withdrawing ? "Processing Transfer..." : `Withdraw Funds (${withdrawType})`}
            </button>

            {message && (
              <div className={`mt-6 p-4 rounded-xl ${message.includes("✅") ? 'bg-green-900/30 text-green-400 border border-green-500/30' : 'bg-red-900/30 text-red-400 border border-red-500/30'} font-mono text-sm animate-fade-in`}>
                {message}
              </div>
            )}
          </div>

          {/* Activity Feed */}
          <div className="bg-[#111] border border-[#333] rounded-2xl p-6">
            <h3 className="text-lg font-semibold text-gray-300 mb-6">Recent Cashflows</h3>
            <div className="space-y-4">
              {stats.recent_transactions?.map((tx, idx) => (
                <div key={idx} className="flex justify-between items-center border-b border-[#222] pb-4 last:border-0">
                  <div>
                    <p className="text-sm text-gray-300">{tx.type.replace('_', ' ')}</p>
                    <p className="text-xs text-gray-500 font-mono mt-1">{tx.source}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-mono text-green-400">+${(tx.amount / 100).toFixed(2)}</p>
                    <p className="text-xs text-gray-500 mt-1">{new Date(tx.date).toLocaleTimeString()}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
          
        </div>
      </div>
    </div>
  );
}
