'use client';

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { CreditCard, Bell, TrendingUp, CheckCircle2, DollarSign, Clock, ArrowRight, Wallet } from 'lucide-react';
import { CardShell } from '../shared/CardShell';

export const CashVisual = () => {
    const [step, setStep] = useState<'monitoring' | 'reminding' | 'collecting' | 'growth'>('monitoring');
    const [cashBalance, setCashBalance] = useState(1250000);

    // Animation Loop
    useEffect(() => {
        const loop = async () => {
            // Phase 1: Monitoring (Show Overdue)
            setStep('monitoring');
            await new Promise(r => setTimeout(r, 2500));

            // Phase 2: Automated Reminder
            setStep('reminding');
            await new Promise(r => setTimeout(r, 2500));

            // Phase 3: Collection (Payment Received)
            setStep('collecting');
            setCashBalance(prev => prev + 450000); // Add payment
            await new Promise(r => setTimeout(r, 3000));

            // Phase 4: Growth (Graph up)
            setStep('growth');
            await new Promise(r => setTimeout(r, 3000));

            // Reset
            setCashBalance(1250000);
            loop();
        };

        loop();
    }, []);

    return (
        <CardShell>
            <div className="h-[600px] relative bg-slate-50 dark:bg-slate-900 overflow-hidden flex flex-col font-sans">

                {/* --- Header --- */}
                <div className="p-6 border-b border-slate-200 dark:border-slate-800 flex justify-between items-start z-10 bg-white/50 dark:bg-slate-900/50 backdrop-blur-sm">
                    <div>
                        <div className="flex items-center gap-2 mb-1">
                            <div className="p-1.5 bg-emerald-100 dark:bg-emerald-900/30 rounded-lg text-emerald-600 dark:text-emerald-400">
                                <Wallet size={16} />
                            </div>
                            <h3 className="text-sm font-bold text-slate-800 dark:text-slate-100 uppercase tracking-wider">
                                Finance Hub
                            </h3>
                        </div>
                        <p className="text-xs text-slate-500 font-mono">CASH FLOW AUTOMATION</p>
                    </div>
                    <div className="text-right">
                        <div className="text-[10px] text-slate-400 uppercase font-bold mb-1">Current Balance</div>
                        <div className="text-xl font-bold text-slate-900 dark:text-white font-mono flex items-center justify-end gap-1">
                            <span className="text-slate-400 text-sm">₹</span>
                            <CountUp value={cashBalance} />
                        </div>
                    </div>
                </div>

                {/* --- Main Content --- */}
                <div className="flex-1 p-6 flex flex-col gap-6 relative z-10">

                    {/* Invoice List */}
                    <div className="space-y-3">
                        <div className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-2 flex justify-between">
                            <span>Accounts Receivable</span>
                            <span className="text-emerald-500">Live Sync</span>
                        </div>

                        {/* Invoice Items */}
                        <InvoiceItem
                            id="#INV-2024-001"
                            client="TechCorp Industries"
                            amount="₹ 1,20,000"
                            status="paid"
                            delay={0}
                        />

                        {/* The Active Invoice */}
                        <motion.div
                            layout
                            className={`relative p-4 rounded-xl border transition-all duration-500 ${step === 'collecting' || step === 'growth'
                                ? 'bg-emerald-50 dark:bg-emerald-900/10 border-emerald-200 dark:border-emerald-800'
                                : 'bg-white dark:bg-slate-800 border-red-200 dark:border-red-900/50 shadow-lg shadow-red-500/5'
                                }`}
                        >
                            <div className="flex justify-between items-start mb-2">
                                <div>
                                    <div className="flex items-center gap-2">
                                        <span className="font-bold text-slate-800 dark:text-white">Global Logistics Ltd</span>
                                        {step === 'monitoring' || step === 'reminding' ? (
                                            <span className="px-2 py-0.5 bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 text-[10px] font-bold rounded-full animate-pulse">
                                                OVERDUE (5 Days)
                                            </span>
                                        ) : (
                                            <motion.span
                                                initial={{ scale: 0 }} animate={{ scale: 1 }}
                                                className="px-2 py-0.5 bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 text-[10px] font-bold rounded-full flex items-center gap-1"
                                            >
                                                <CheckCircle2 size={10} /> PAID
                                            </motion.span>
                                        )}
                                    </div>
                                    <div className="text-xs text-slate-500 mt-1">Ref: #INV-2024-002 • Due: Oct 12</div>
                                </div>
                                <div className="text-right">
                                    <div className="font-bold text-slate-900 dark:text-white">₹ 4,50,000</div>
                                </div>
                            </div>

                            {/* Action Status Bar */}
                            <div className="mt-3 pt-3 border-t border-slate-100 dark:border-slate-700/50 flex items-center justify-between h-8">
                                <AnimatePresence mode="wait">
                                    {step === 'monitoring' && (
                                        <motion.div
                                            key="mon"
                                            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                                            className="flex items-center gap-2 text-xs text-red-500"
                                        >
                                            <Clock size={12} />
                                            <span>Payment pending action</span>
                                        </motion.div>
                                    )}
                                    {step === 'reminding' && (
                                        <motion.div
                                            key="rem"
                                            initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0 }}
                                            className="flex items-center gap-2 text-xs text-blue-500 font-medium"
                                        >
                                            <Bell size={12} className="animate-swing" />
                                            <span>Sending automated reminder...</span>
                                        </motion.div>
                                    )}
                                    {(step === 'collecting' || step === 'growth') && (
                                        <motion.div
                                            key="col"
                                            initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }}
                                            className="flex items-center gap-2 text-xs text-emerald-600 dark:text-emerald-400 font-bold"
                                        >
                                            <CheckCircle2 size={12} />
                                            <span>Payment collected via Gateway</span>
                                        </motion.div>
                                    )}
                                </AnimatePresence>
                            </div>
                        </motion.div>

                        <InvoiceItem
                            id="#INV-2024-003"
                            client="Apex Construction"
                            amount="₹ 85,000"
                            status="pending"
                            delay={0.2}
                        />
                    </div>

                    {/* Cash Flow Graph */}
                    <div className="flex-1 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-4 relative overflow-hidden flex flex-col justify-end">
                        <div className="absolute top-4 left-4 text-xs font-bold text-slate-400 uppercase">Cash Flow Projection</div>

                        {/* Graph Bars */}
                        <div className="flex items-end justify-between gap-2 h-32 px-2">
                            {[40, 65, 45, 80, 55, 90].map((h, i) => (
                                <div key={i} className="w-full bg-slate-100 dark:bg-slate-700 rounded-t-sm relative overflow-hidden group">
                                    <motion.div
                                        className="absolute bottom-0 left-0 right-0 bg-blue-500/20 dark:bg-blue-500/40"
                                        initial={{ height: 0 }}
                                        animate={{ height: `${h}%` }}
                                        transition={{ duration: 1, delay: i * 0.1 }}
                                    />
                                    {/* The Growth Bar */}
                                    {i === 5 && (
                                        <motion.div
                                            className="absolute bottom-0 left-0 right-0 bg-emerald-500"
                                            initial={{ height: "40%" }}
                                            animate={{ height: step === 'growth' ? "90%" : "40%" }}
                                            transition={{ type: "spring", stiffness: 100 }}
                                        />
                                    )}
                                </div>
                            ))}
                        </div>

                        {/* Floating Growth Badge */}
                        <AnimatePresence>
                            {step === 'growth' && (
                                <motion.div
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    exit={{ opacity: 0 }}
                                    className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-emerald-500 text-white px-3 py-1.5 rounded-full shadow-lg shadow-emerald-500/30 flex items-center gap-2"
                                >
                                    <TrendingUp size={14} />
                                    <span className="text-xs font-bold">+35% Growth</span>
                                </motion.div>
                            )}
                        </AnimatePresence>
                    </div>
                </div>

                {/* Background Decor */}
                <div className="absolute inset-0 pointer-events-none">
                    <div className="absolute -top-20 -right-20 w-64 h-64 bg-emerald-500/5 rounded-full blur-3xl" />
                    <div className="absolute -bottom-20 -left-20 w-64 h-64 bg-blue-500/5 rounded-full blur-3xl" />
                </div>
            </div>
        </CardShell>
    );
};

const InvoiceItem = ({ id, client, amount, status, delay }: any) => (
    <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay }}
        className="p-3 rounded-lg border border-slate-100 dark:border-slate-800 bg-white/50 dark:bg-slate-900/50 flex justify-between items-center"
    >
        <div className="flex items-center gap-3">
            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${status === 'paid' ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30' : 'bg-slate-100 text-slate-500 dark:bg-slate-800'
                }`}>
                {status === 'paid' ? <CheckCircle2 size={14} /> : <Clock size={14} />}
            </div>
            <div>
                <div className="text-xs font-bold text-slate-700 dark:text-slate-300">{client}</div>
                <div className="text-[10px] text-slate-400">{id}</div>
            </div>
        </div>
        <div className="text-xs font-mono font-medium text-slate-600 dark:text-slate-400">{amount}</div>
    </motion.div>
);

const CountUp = ({ value }: { value: number }) => {
    const [display, setDisplay] = useState(value);

    useEffect(() => {
        let start = display;
        const end = value;
        if (start === end) return;

        const duration = 1000;
        const startTime = performance.now();

        const update = (currentTime: number) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);

            // Ease out quart
            const ease = 1 - Math.pow(1 - progress, 4);

            const current = start + (end - start) * ease;
            setDisplay(Math.round(current));

            if (progress < 1) {
                requestAnimationFrame(update);
            }
        };

        requestAnimationFrame(update);
    }, [value]);

    return <span>{display.toLocaleString('en-IN')}</span>;
};
