"use client";

import { useEffect, useState } from "react";
import Header from "@/components/layout/Header";
import Footer from "@/components/layout/Footer";
import { api } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";
import { useSettings } from "@/context/SettingsContext";
import { Wallet, ArrowUpRight, ArrowDownLeft, Clock } from "lucide-react";
import { useRouter } from "next/navigation";
import { Skeleton } from "@/components/ui/Skeleton";

export default function WalletPage() {
  const { user, isLoading } = useAuth();
  const { currency, formatMoney } = useSettings();
  const router = useRouter();
  const [balance, setBalance] = useState("0.00");
  const [transactions, setTransactions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!isLoading && !user) {
      router.push("/login?redirect=/wallet");
      return;
    }

    if (user) {
      fetchWalletData();
    }
  }, [user, isLoading]);

  const fetchWalletData = async () => {
    try {
      const res = await api.getWallet();
      if (res.data) {
        setBalance(res.data.balance);
        setTransactions(res.data.transactions);
      }
    } catch (error) {
      // console.error("Failed to fetch wallet:", error);
    } finally {
      setLoading(false);
    }
  };

  if (isLoading || loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Header />
        <div className="container mx-auto px-4 py-8">
            <Skeleton className="h-48 w-full rounded-2xl mb-8" />
            <Skeleton className="h-10 w-48 mb-4" />
            <div className="space-y-4">
                {[1, 2, 3].map((i) => (
                    <Skeleton key={i} className="h-20 w-full rounded-xl" />
                ))}
            </div>
        </div>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        <h1 className="text-2xl font-bold mb-6 text-slate-800">My Wallet</h1>

        {/* Balance Card */}
        <div className="bg-gradient-to-r from-emerald-600 to-teal-600 rounded-2xl p-8 text-white shadow-lg mb-8 relative overflow-hidden">
            <div className="absolute top-0 right-0 p-8 opacity-10">
                <Wallet size={120} />
            </div>
            <p className="text-emerald-100 font-medium mb-2">Available Balance</p>
            <h2 className="text-4xl font-bold">{formatMoney(Number(balance))}</h2>
            
            <div className="mt-6 flex gap-3">
                <button className="bg-white text-emerald-700 px-6 py-2 rounded-full font-semibold text-sm hover:bg-emerald-50 transition-colors shadow-sm">
                    + Add Money
                </button>
            </div>
        </div>

        {/* Transactions */}
        <div className="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
            <div className="p-6 border-b border-slate-100">
                <h3 className="font-bold text-lg text-slate-800">Recent Transactions</h3>
            </div>
            
            {transactions.length === 0 ? (
                <div className="p-12 text-center text-slate-400">
                    <Clock className="mx-auto mb-3 opacity-50" size={48} />
                    <p>No transactions yet</p>
                </div>
            ) : (
                <div className="divide-y divide-slate-100">
                    {transactions.map((tx) => (
                        <div key={tx.id} className="p-4 sm:p-6 flex items-center justify-between hover:bg-slate-50 transition-colors">
                            <div className="flex items-center gap-4">
                                <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                                    tx.type === 'credit' ? 'bg-emerald-100 text-emerald-600' : 'bg-rose-100 text-rose-600'
                                }`}>
                                    {tx.type === 'credit' ? <ArrowDownLeft size={20} /> : <ArrowUpRight size={20} />}
                                </div>
                                <div>
                                    <p className="font-semibold text-slate-800">{tx.description}</p>
                                    <p className="text-xs text-slate-500">{new Date(tx.created_at).toLocaleDateString()}</p>
                                </div>
                            </div>
                            <div className={`font-bold ${
                                tx.type === 'credit' ? 'text-emerald-600' : 'text-slate-800'
                            }`}>
                                {tx.type === 'credit' ? '+' : '-'}{formatMoney(Number(tx.amount))}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
      </main>

      <Footer />
    </div>
  );
}
