import React, { useState, useEffect } from 'react';
import clientPortalService from '../services/clientPortalService';
import {
    CreditCard,
    Clock,
    CheckCircle,
    ArrowRight,
    Receipt,
    FileText,
    TrendingUp,
    LayoutDashboard,
    Calendar,
    DollarSign,
    Zap,
    ShieldCheck
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { clsx } from 'clsx';

const StatCard = ({ title, value, icon: Icon, colorClass, subtitle }) => (
    <div className="premium-card p-6 sm:p-8 group hover:scale-[1.02] transition-all duration-500">
        <div className="flex justify-between items-start mb-6 gap-4">
            <div className={clsx("p-3.5 sm:p-4 rounded-[1.25rem] sm:rounded-[1.5rem] text-white shadow-xl transition-transform group-hover:rotate-12 duration-500 shrink-0", colorClass)}>
                <Icon className="w-5 h-5 sm:w-6 sm:h-6 shrink-0" />
            </div>
            <div className="text-right min-w-0">
                <span className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest truncate block">{subtitle}</span>
            </div>
        </div>
        <div className="space-y-1 min-w-0">
            <p className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] truncate">{title}</p>
            <h3 className="text-2xl sm:text-3xl font-black text-slate-800 dark:text-white tracking-tighter italic truncate">
                {value}
            </h3>
        </div>
    </div>
);

const ClientDashboard = () => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);

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

    const fetchDashboard = async () => {
        try {
            const res = await clientPortalService.getDashboard();
            setData(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    if (loading) return (
        <div className="min-h-[60vh] flex flex-col items-center justify-center gap-4 animate-pulse">
            <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
            <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Synchronizing Portal Data...</p>
        </div>
    );

    return (
        <div className="space-y-10 animate-slide-up pb-20">
            {/* Premium Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                    <div className="p-3 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                        <LayoutDashboard className="w-6 h-6 sm:w-8 sm:h-8 shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-xl sm:text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight leading-none truncate">Client Nexus</h1>
                        <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest whitespace-nowrap">Operation Control Center</span>
                            <div className="w-1 h-1 bg-slate-300 dark:bg-slate-700 rounded-full shrink-0"></div>
                            <span className="text-[10px] font-black text-primary uppercase tracking-widest whitespace-nowrap truncate">Protocol Active</span>
                        </div>
                    </div>
                </div>
                <div className="flex items-center gap-3 px-5 sm:px-6 h-12 bg-emerald-500/10 border border-emerald-500/20 rounded-2xl w-full md:w-auto justify-center shrink-0">
                    <ShieldCheck className="w-4 h-4 text-emerald-500 shrink-0" />
                    <span className="text-[10px] font-black text-emerald-600 dark:text-emerald-400 uppercase tracking-widest whitespace-nowrap">Secure Core Link</span>
                </div>
            </div>

            {/* Metrics Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
                <StatCard
                    title="Outstanding Inertia"
                    value={`$${Number(data.metrics.outstandingBalance).toLocaleString()}`}
                    icon={CreditCard}
                    colorClass="bg-rose-500 shadow-rose-500/20"
                    subtitle="Liability Delta"
                />
                <StatCard
                    title="Settled Tokens"
                    value={data.metrics.paidInvoices}
                    icon={CheckCircle}
                    colorClass="bg-emerald-500 shadow-emerald-500/20"
                    subtitle="Closed Vectors"
                />
                <StatCard
                    title="Proposal Matrix"
                    value={data.metrics.totalInvoices}
                    icon={Clock}
                    colorClass="bg-amber-500 shadow-amber-500/20"
                    subtitle="Active Estimates"
                />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 sm:gap-10">
                {/* Recent Payments */}
                <div className="premium-card flex flex-col h-full overflow-hidden">
                    <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-900/40">
                        <div className="flex items-center gap-3 sm:gap-4">
                            <div className="p-2.5 sm:p-3 bg-primary/10 rounded-2xl text-primary shrink-0">
                                <Receipt className="w-5 h-5 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h3 className="text-base sm:text-lg font-black text-slate-800 dark:text-white tracking-tight truncate">Liquidity Events</h3>
                                <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest truncate">Recent Inbound Logic</p>
                            </div>
                        </div>
                        <Link to="/portal/payments" className="btn-secondary !py-2 !px-4 text-[10px] flex items-center gap-2 shrink-0 h-9 sm:h-auto">
                            <span className="hidden sm:inline">Audit Trail</span>
                            <ArrowRight className="w-3 h-3 shrink-0" />
                        </Link>
                    </div>
                    <div className="p-6 sm:p-8 space-y-4 flex-1">
                        {data.recentPayments.length > 0 ? data.recentPayments.map(p => (
                            <div key={p.id} className="group flex justify-between items-center p-4 sm:p-5 bg-slate-50/50 dark:bg-slate-900/40 rounded-[1.25rem] sm:rounded-[1.5rem] border border-slate-100 dark:border-slate-800 hover:border-primary/30 transition-all duration-300 gap-4">
                                <div className="flex items-center gap-3 sm:gap-4 min-w-0">
                                    <div className="w-10 h-10 bg-white dark:bg-slate-800 rounded-xl flex items-center justify-center text-primary border border-slate-100 dark:border-slate-700 shadow-sm group-hover:scale-110 transition-transform shrink-0">
                                        <TrendingUp className="w-5 h-5 shrink-0" />
                                    </div>
                                    <div className="min-w-0">
                                        <p className="text-sm font-black text-slate-800 dark:text-white tracking-tight truncate">Invoice #{p.Invoice?.invoiceNumber}</p>
                                        <p className="text-[9px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.2em] truncate">{p.paymentMethod}</p>
                                    </div>
                                </div>
                                <div className="text-right shrink-0">
                                    <p className="text-sm font-black text-emerald-500 italic whitespace-nowrap">+$ {Number(p.amount).toLocaleString()}</p>
                                    <p className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest mt-0.5 whitespace-nowrap">{new Date(p.paymentDate).toLocaleDateString()}</p>
                                </div>
                            </div>
                        )) : (
                            <div className="flex flex-col items-center justify-center py-12 sm:py-20 opacity-30 grayscale text-center">
                                <DollarSign className="w-12 h-12 mb-4 shrink-0" />
                                <p className="text-[10px] font-black uppercase tracking-widest">Zero liquidity events detected.</p>
                            </div>
                        )}
                    </div>
                </div>

                {/* Upcoming Billing */}
                <div className="premium-card flex flex-col h-full overflow-hidden">
                    <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-900/40">
                        <div className="flex items-center gap-3 sm:gap-4">
                            <div className="p-2.5 sm:p-3 bg-amber-500/10 rounded-2xl text-amber-500 shrink-0">
                                <Zap className="w-5 h-5 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h3 className="text-base sm:text-lg font-black text-slate-800 dark:text-white tracking-tight truncate">Cycle Persistence</h3>
                                <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest truncate">Upcoming Billing Signals</p>
                            </div>
                        </div>
                    </div>
                    <div className="p-6 sm:p-8 space-y-4 flex-1">
                        {data.upcomingBilling.length > 0 ? data.upcomingBilling.map((sub, i) => (
                            <div key={i} className="group flex justify-between items-center p-4 sm:p-5 border-2 border-dashed border-slate-100 dark:border-slate-800 rounded-[1.25rem] sm:rounded-[1.5rem] hover:border-amber-500/30 transition-all duration-300 gap-4">
                                <div className="flex items-center gap-3 sm:gap-4 min-w-0">
                                    <div className="w-10 h-10 bg-slate-50 dark:bg-slate-900 rounded-xl flex items-center justify-center text-amber-500 border border-slate-100 dark:border-slate-800 shadow-sm group-hover:scale-110 transition-transform shrink-0">
                                        <Calendar className="w-5 h-5 shrink-0" />
                                    </div>
                                    <div className="min-w-0">
                                        <p className="text-sm font-black text-slate-600 dark:text-slate-400 tracking-tight truncate">{sub.name}</p>
                                        <p className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-[0.2em] truncate">Next: {sub.nextBillingDate}</p>
                                    </div>
                                </div>
                                <p className="text-sm font-black text-slate-800 dark:text-white italic tracking-tighter shrink-0 whitespace-nowrap">$ {Number(sub.amount).toLocaleString()}</p>
                            </div>
                        )) : (
                            <div className="flex flex-col items-center justify-center py-12 sm:py-20 opacity-30 grayscale text-center">
                                <Zap className="w-12 h-12 mb-4 shrink-0" />
                                <p className="text-[10px] font-black uppercase tracking-widest">Zero persistence cycles detected.</p>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ClientDashboard;
