'use client';

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Mail, MessageSquare, Bell, TrendingUp, DollarSign, Boxes, CheckCircle2, Zap, Clock, ArrowRight, User } from 'lucide-react';
import { CardShell } from '../shared/CardShell';

// Mock Data for Generator
const TEMPLATES = [
    { type: 'sales', icon: User, title: 'New Inquiry: TechSolution', text: 'New Inquiry: TechSolution', priority: 'high', action: 'Assigning to Sarah' },
    { type: 'sales', icon: TrendingUp, title: 'Pending Offer #1023', text: 'Client viewed proposal 3x. Follow up?', priority: 'high', action: 'Auto-Drafting Email' },
    { type: 'finance', icon: DollarSign, title: 'Payment Overdue Invoice #992', text: 'ABC Corp payment pending (5 days).', priority: 'medium', action: 'Sending Reminder' },
    { type: 'finance', icon: DollarSign, title: 'Payment Recieved for Invoice #992', text: 'ABC Corp payment recieved for invoice #992.', priority: 'medium', action: 'Sending Reminder' },
    
    { type: 'ops', icon: Boxes, title: 'Pending Offer: Valve-A', text: 'Pending Offer: Valve-A', priority: 'critical', action: 'Notifying Purchase' },
  
];

export const MessagingVisual = () => {
    const [messages, setMessages] = useState<any[]>([]);
    const [processedCount, setProcessedCount] = useState(124);

    // Simulation Loop
    useEffect(() => {
        // Sequentially add messages in TEMPLATES order, looping after end
        let idx = 0;
        let timeout1: NodeJS.Timeout | null = null;
        let interval: NodeJS.Timeout | null = null;

        // Immediate first message
        addMessage(idx);

        timeout1 = setTimeout(() => {
            idx = (idx + 1) % TEMPLATES.length;
            addMessage(idx);

            interval = setInterval(() => {
                idx = (idx + 1) % TEMPLATES.length;
                addMessage(idx);
            }, 3500);
        }, 1000);

        return () => {
            if (timeout1) clearTimeout(timeout1);
            if (interval) clearInterval(interval);
        };
    }, []);

    const addMessage = (idx: number) => {
        const template = TEMPLATES[idx];
        const newMsg = {
            id: Date.now(),
            ...template,
            status: 'analyzing', // analyzing -> processing -> sent
            timestamp: 'Just now'
        };

        setMessages(prev => [newMsg, ...prev].slice(0, 4)); // Keep top 4

        // Trigger lifecycle for this specific message
        setTimeout(() => updateMessageStatus(newMsg.id, 'processing'), 1500);
        setTimeout(() => {
            updateMessageStatus(newMsg.id, 'sent');
            setProcessedCount(c => c + 1);
        }, 3000);
    };

    const updateMessageStatus = (id: number, status: string) => {
        setMessages(prev => prev.map(m => m.id === id ? { ...m, status } : m));
    };

    const getStyles = (type: string) => {
        switch (type) {
            case 'sales': return 'bg-blue-500 text-blue-500 border-blue-200 bg-blue-50';
            case 'finance': return 'bg-emerald-500 text-emerald-500 border-emerald-200 bg-emerald-50';
            case 'ops': return 'bg-amber-500 text-amber-500 border-amber-200 bg-amber-50';
            default: return 'bg-slate-500';
        }
    };

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

                {/* --- Background Effects --- */}
                <div className="absolute inset-0 opacity-[0.03]"
                    style={{ backgroundImage: 'radial-gradient(#64748b 1px, transparent 1px)', backgroundSize: '24px 24px' }} />
                <div className="absolute -top-20 -right-20 w-64 h-64 bg-indigo-500/10 blur-[80px] rounded-full pointer-events-none" />

                {/* --- Header --- */}
                <div className="p-5 border-b border-slate-200/50 dark:border-slate-700/50 flex justify-between items-center backdrop-blur-sm z-20">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center shadow-lg shadow-indigo-500/20">
                            <Bell size={20} className="text-white" />
                        </div>
                        <div>
                            <h4 className="text-sm font-bold text-slate-900 dark:text-white">Notification Hub</h4>
                            <div className="flex items-center gap-1.5">
                                <div className="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse" />
                                <span className="text-[10px] text-slate-500 dark:text-slate-400 font-mono">SYSTEM ACTIVE</span>
                            </div>
                        </div>
                    </div>

                    <div className="flex flex-col items-end">
                        <span className="text-2xl font-bold text-slate-800 dark:text-white tabular-nums leading-none">
                            {processedCount}
                        </span>
                        <span className="text-[10px] text-slate-400 uppercase font-bold tracking-wider">Automations Run</span>
                    </div>
                </div>

                {/* --- Feed Container --- */}
                <div className="flex-1 p-5 relative z-10 overflow-hidden">
                    {/* "Stream" Line */}
                    <div className="absolute left-9 top-0 bottom-0 w-px bg-slate-200 dark:bg-slate-800 -z-10" />

                    <AnimatePresence mode="popLayout">
                        {messages.map((msg) => {
                            const style = getStyles(msg.type);
                            const isAnalyzing = msg.status === 'analyzing';
                            const isProcessing = msg.status === 'processing';
                            const isSent = msg.status === 'sent';

                            return (
                                <motion.div
                                    key={msg.id}
                                    layout
                                    initial={{ opacity: 0, x: -50, scale: 0.9 }}
                                    animate={{ opacity: 1, x: 0, scale: 1 }}
                                    exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.2 } }}
                                    transition={{ type: "spring", stiffness: 400, damping: 30 }}
                                    className="relative mb-3 pl-12"
                                >
                                    {/* Timeline Node */}
                                    <div className={`
                          absolute left-0 top-3 w-8 h-8 rounded-full border-2 border-white dark:border-slate-800 flex items-center justify-center z-10 transition-colors duration-500
                          ${isSent ? 'bg-green-500 text-white shadow-green-500/30' : 'bg-white dark:bg-slate-800 text-slate-400 shadow-sm'}
                       `}>
                                        {isSent ? <CheckCircle2 size={16} /> : <msg.icon size={14} />}
                                    </div>

                                    {/* Card Body */}
                                    <div className={`
                          p-3 rounded-xl border backdrop-blur-md transition-all duration-500
                          ${isSent
                                            ? 'bg-white/80 dark:bg-slate-800/80 border-slate-200 dark:border-slate-700'
                                            : 'bg-white/50 dark:bg-slate-900/50 border-slate-100 dark:border-slate-800'}
                       `}>
                                        <div className="flex justify-between items-start mb-1">
                                            <div className="flex items-center gap-2">
                                                <span className={`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${style.split(' ').filter(c => c.startsWith('bg-') && !c.includes('500')).join(' ')} ${style.split(' ').find(c => c.startsWith('text-'))}`}>
                                                    {msg.type}
                                                </span>
                                                {isAnalyzing && (
                                                    <span className="text-[10px] text-slate-400 animate-pulse flex items-center gap-1">
                                                        <Zap size={10} /> AI Analyzing...
                                                    </span>
                                                )}
                                            </div>
                                            <span className="text-[10px] text-slate-400">{msg.timestamp}</span>
                                        </div>

                                        <h5 className="text-sm font-bold text-slate-800 dark:text-slate-100">{msg.title}</h5>
                                        <p className="text-xs text-slate-500 dark:text-slate-400 mb-2">{msg.text}</p>

                                        {/* Action Footer */}
                                        <div className="flex items-center justify-between h-6 overflow-hidden">
                                            <AnimatePresence mode="wait">
                                                {isAnalyzing && (
                                                    <motion.div
                                                        key="step1"
                                                        initial={{ y: 10, opacity: 0 }}
                                                        animate={{ y: 0, opacity: 1 }}
                                                        exit={{ y: -10, opacity: 0 }}
                                                        className="flex items-center gap-2"
                                                    >
                                                        <div className="w-24 h-2 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden">
                                                            <motion.div
                                                                className="h-full bg-slate-300 dark:bg-slate-600"
                                                                animate={{ width: ["0%", "100%"] }}
                                                                transition={{ duration: 1.5, ease: "linear" }}
                                                            />
                                                        </div>
                                                    </motion.div>
                                                )}

                                                {isProcessing && (
                                                    <motion.div
                                                        key="step2"
                                                        initial={{ y: 10, opacity: 0 }}
                                                        animate={{ y: 0, opacity: 1 }}
                                                        exit={{ y: -10, opacity: 0 }}
                                                        className="flex items-center gap-2 text-xs text-indigo-500 font-medium"
                                                    >
                                                        <Clock size={12} className="animate-spin" />
                                                        {msg.action}...
                                                    </motion.div>
                                                )}

                                                {isSent && (
                                                    <motion.div
                                                        key="step3"
                                                        initial={{ y: 10, opacity: 0 }}
                                                        animate={{ y: 0, opacity: 1 }}
                                                        className="flex items-center gap-2 text-xs text-green-600 dark:text-green-400 font-bold"
                                                    >
                                                        <CheckCircle2 size={12} />
                                                        Action Executed
                                                    </motion.div>
                                                )}
                                            </AnimatePresence>

                                            {/* Priority Badge */}
                                            <div className={`w-2 h-2 rounded-full ${msg.priority === 'critical' ? 'bg-red-500 animate-ping' : 'bg-slate-300'}`} />
                                        </div>
                                    </div>
                                </motion.div>
                            );
                        })}
                    </AnimatePresence>
                </div>

                {/* Footer Fade */}
                <div className="absolute bottom-0 left-0 w-full h-12 bg-gradient-to-t from-slate-50 dark:from-slate-900 to-transparent pointer-events-none" />

            </div>
        </CardShell>
    );
};