'use client';

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { FileText, CheckCircle2, AlertCircle, Calculator, ShieldCheck, PenTool } from 'lucide-react';
import { CardShell } from '../shared/CardShell';

// Mock Invoice Data
const LINE_ITEMS = [
    { id: 1, desc: "Industrial Pump Set (X-200)", qty: 2, price: 12500 },
    { id: 2, desc: "Installation Service", qty: 1, price: 4500 },
    { id: 3, desc: "Extended Warranty (1yr)", qty: 2, price: 1200 },
];

type LineItem = {
    id: number;
    desc: string;
    qty: number;
    price: number;
};

export const QuoteVisual = () => {
    const [items, setItems] = useState<LineItem[]>([]);
    const [stage, setStage] = useState<'drafting' | 'validating' | 'approved'>('drafting');
    const [total, setTotal] = useState(0);

    // Animation Sequence
    useEffect(() => {
        let currentTotal = 0;

        const runSequence = () => {
            setItems([]);
            setTotal(0);
            setStage('drafting');

            // 1. Add Items sequentially
            LINE_ITEMS.forEach((item, index) => {
                setTimeout(() => {
                    setItems(prev => [...prev, item]);
                    currentTotal += (item.qty * item.price);
                    setTotal(currentTotal);
                }, (index + 1) * 800);
            });

            // 2. Start Validation (Margin Check)
            setTimeout(() => {
                setStage('validating');
            }, 3500);

            // 3. Approve
            setTimeout(() => {
                setStage('approved');
            }, 5500);

            // 4. Reset Loop
            setTimeout(runSequence, 9000);
        };

        runSequence();
        return () => { };
    }, []);

    const formatCurrency = (val: number) =>
        new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumSignificantDigits: 3 }).format(val);

    return (
        <CardShell>
            <div className="w-full h-[600px] bg-slate-50 dark:bg-slate-900/50 rounded-3xl border border-slate-200 dark:border-slate-800 relative flex flex-col items-center justify-center p-6 font-sans overflow-hidden">

                {/* Background Grid */}
                <div className="absolute inset-0 opacity-[0.03] pointer-events-none"
                    style={{ backgroundImage: 'linear-gradient(#8b5cf6 1px, transparent 1px), linear-gradient(to right, #8b5cf6 1px, transparent 1px)', backgroundSize: '32px 32px' }} />

                {/* --- Main Invoice Card --- */}
                <motion.div
                    layout
                    className="w-full max-w-sm bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 overflow-hidden relative z-10"
                >
                    {/* Header */}
                    <div className="bg-slate-50 dark:bg-slate-900/50 p-4 border-b border-slate-100 dark:border-slate-700 flex justify-between items-start">
                        <div className="flex gap-3">
                            <div className="w-10 h-10 bg-violet-100 dark:bg-violet-900/30 rounded-lg flex items-center justify-center text-violet-600 dark:text-violet-400">
                                <FileText size={20} />
                            </div>
                            <div>
                                <h3 className="text-sm font-bold text-slate-900 dark:text-white">Quote #Q-2024</h3>
                                <div className="text-[10px] text-slate-500">To: Acme Corp Industries</div>
                            </div>
                        </div>
                        <div className="text-right">
                            <div className="text-[10px] uppercase font-bold text-slate-400">Status</div>
                            <div className={`text-xs font-bold ${stage === 'approved' ? 'text-green-500' : 'text-amber-500'}`}>
                                {stage === 'drafting' ? 'DRAFTING...' : stage === 'validating' ? 'CHECKING...' : 'APPROVED'}
                            </div>
                        </div>
                    </div>

                    {/* Body: Line Items */}
                    <div className="p-4 min-h-[220px] relative">
                        <div className="space-y-3">
                            <AnimatePresence>
                                {items.map((item) => (
                                    <motion.div
                                        key={item.id}
                                        initial={{ opacity: 0, x: -20, height: 0 }}
                                        animate={{ opacity: 1, x: 0, height: 'auto' }}
                                        className="flex justify-between items-center text-xs border-b border-slate-50 dark:border-slate-700/50 pb-2"
                                    >
                                        <div>
                                            <div className="font-medium text-slate-700 dark:text-slate-200">{item.desc}</div>
                                            <div className="text-[10px] text-slate-400">Qty: {item.qty}</div>
                                        </div>
                                        <div className="font-mono font-semibold text-slate-600 dark:text-slate-300">
                                            {formatCurrency(item.price * item.qty)}
                                        </div>
                                    </motion.div>
                                ))}
                            </AnimatePresence>
                        </div>

                        {/* Total Section */}
                        <div className="mt-6 pt-4 border-t border-slate-100 dark:border-slate-700 flex justify-between items-end">
                            <div className="text-xs text-slate-500">Total Value</div>
                            <motion.div
                                key={total} // Triggers animation on change
                                initial={{ scale: 1.2, color: '#8b5cf6' }}
                                animate={{ scale: 1, color: 'currentColor' }}
                                className="text-lg font-bold font-mono text-slate-900 dark:text-white"
                            >
                                {formatCurrency(total)}
                            </motion.div>
                        </div>

                        {/* Stamp Overlay */}
                        {stage === 'validating' && (
                            <motion.div
                                initial={{ scale: 2, opacity: 0, rotate: -15 }}
                                animate={{ scale: 1, opacity: 1, rotate: -12 }}
                                transition={{ type: "spring", stiffness: 300, damping: 12 }}
                                className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 border-[3px] border-green-500 text-green-500 px-6 py-2 rounded-lg text-2xl font-black uppercase tracking-widest opacity-80 mix-blend-multiply dark:mix-blend-plus-lighter z-50 pointer-events-none"
                                style={{ textShadow: "0 0 20px rgba(34, 197, 94, 0.5)" }}
                            >
                                Order Received
                            </motion.div>
                        )}
                            {stage === 'approved' && (
                            <motion.div
                                initial={{ scale: 2, opacity: 0, rotate: -15 }}
                                animate={{ scale: 1, opacity: 1, rotate: -12 }}
                                transition={{ type: "spring", stiffness: 300, damping: 12 }}
                                className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 border-[3px] border-blue-500 text-pink-500 px-6 py-2 rounded-lg text-2xl font-black uppercase tracking-widest opacity-80 mix-blend-multiply dark:mix-blend-plus-lighter z-50 pointer-events-none"
                                style={{ textShadow: "0 0 20px rgba(34, 197, 94, 0.5)" }}
                            >
                            Issued Proforma Invoice
                            </motion.div>
                        )}
                    </div>

                    {/* Footer: Intelligence Engine */}
                    <div className="bg-slate-50 dark:bg-slate-900/80 p-3 border-t border-slate-100 dark:border-slate-700 flex items-center justify-between">

                        {/* Intelligent Margin Check UI */}
                        <div className="flex items-center gap-2">
                            <div className={`p-1.5 rounded-md transition-colors duration-500 ${stage === 'validating' ? 'bg-amber-100 text-amber-600' :
                                stage === 'approved' ? 'bg-green-100 text-green-600' : 'bg-slate-100 text-slate-400'
                                }`}>
                                <ShieldCheck size={14} />
                            </div>
                            <div>
                                <div className="text-[10px] font-bold text-slate-500 uppercase tracking-wide"> Margin Guard</div>
                                <div className="flex items-center gap-1 h-3 overflow-hidden">
                                    <motion.div
                                        animate={{ y: stage === 'validating' ? 0 : stage === 'approved' ? -12 : 0 }}
                                        className="flex flex-col"
                                    >
                                        <span className="text-[10px] text-slate-400">Idle</span>
                                        <span className="text-[10px] text-amber-500 font-bold">Validating...</span>
                                        <span className="text-[10px] text-green-500 font-bold">Margin Safe</span>
                                    </motion.div>
                                </div>
                            </div>
                        </div>

                        {/* Digital Signature */}
                        <div className="w-24 h-8 relative">
                            {stage === 'approved' && (
                                <>
                                    <div className="absolute bottom-0 left-0 w-full h-[1px] bg-slate-300" />
                                    <svg className="absolute -bottom-2 left-0 w-full h-full pointer-events-none" viewBox="0 0 100 40">
                                        <motion.path
                                            d="M 10 25 Q 25 10 35 25 T 55 25 T 75 20"
                                            fill="none"
                                            stroke="#8b5cf6"
                                            strokeWidth="2"
                                            initial={{ pathLength: 0 }}
                                            animate={{ pathLength: 1 }}
                                            transition={{ duration: 0.8, ease: "easeOut" }}
                                        />
                                    </svg>
                                    <motion.div
                                        initial={{ opacity: 0 }}
                                        animate={{ opacity: 1 }}
                                        transition={{ delay: 0 }}
                                        className="absolute -bottom-4 right-0 text-[8px] text-slate-400 font-mono"
                                    >
                                        Signed via Auto-Auth
                                    </motion.div>
                                </>
                            )}
                        </div>

                    </div>
                </motion.div>

                {/* Floating Context Tooltips (Decorations) */}
                <AnimatePresence>
                    {stage === 'drafting' && (
                        <motion.div
                            initial={{ opacity: 0, x: 20 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, scale: 0.9 }}
                            className="absolute right-10 top-1/3 bg-slate-800 text-white p-3 rounded-lg shadow-xl text-xs z-20 max-w-[150px]"
                        >
                            <div className="flex items-center gap-2 mb-1 text-green-400 font-bold">
                                <Calculator size={12} />
                                <span>Analysis</span>
                            </div>
                            QBD - quantity based discount of additional 5% possible for greater than 10 units.
                        </motion.div>
                    )}
                </AnimatePresence>

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