'use client';

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Sparkles, AlertTriangle, CheckCircle2, Package, RefreshCw, Activity } from 'lucide-react';
import { CardShell } from '../shared/CardShell';

// Types for our inventory items
interface InventoryItem {
    id: string;
    name: string;
    sku: string;
    maxStock: number;
    currentStock: number;
    threshold: number;
    unit: string;
}

export const PurchaseVisual = () => {
    // Animation state sequence:
    // 'monitoring' -> 'depleting' -> 'critical' -> 'ordering' -> 'incoming' -> 'restocking'
    const [phase, setPhase] = useState<'monitoring' | 'depleting' | 'critical' | 'ordering' | 'incoming' | 'restocking'>('monitoring');

    // Mock Data
    const items: InventoryItem[] = [
        { id: '1', name: 'Steel Pipes', sku: 'SP-204', maxStock: 1000, currentStock: 850, threshold: 200, unit: 'units' },
        { id: '2', name: 'Valves Type A', sku: 'VA-992', maxStock: 500, currentStock: 420, threshold: 100, unit: 'units' },
        { id: '3', name: 'Connectors', sku: 'CN-101', maxStock: 2000, currentStock: 1800, threshold: 300, unit: 'units' },
    ];

    const incomingDateLabel = (() => {
        const now = new Date();
        const nextYear = now.getMonth() === 0 ? now.getFullYear() : now.getFullYear() + 1;
        // Keep it deterministic and "system-like" rather than random: Jan 12
        const incoming = new Date(nextYear, 0, 12);
        return incoming.toLocaleDateString(undefined, { month: 'long', day: 'numeric', year: 'numeric' });
    })();

    // Animation Loop Controller
    useEffect(() => {
        let cancelled = false;
        let timeoutId: ReturnType<typeof setTimeout> | null = null;

        const sleep = (ms: number) =>
            new Promise<void>((resolve) => {
                timeoutId = setTimeout(resolve, ms);
            });

        (async () => {
            while (!cancelled) {
                // Phase 1: Monitoring (Stable)
                setPhase('monitoring');
                await sleep(800);
                if (cancelled) break;

                // Phase 2: Depleting (Valves drop)
                setPhase('depleting');
                await sleep(1500);
                if (cancelled) break;

                // Phase 3: Critical (Threshold crossed)
                setPhase('critical');
                await sleep(1500);
                if (cancelled) break;

                // Phase 4: Ordering (Auto-PO triggers)
                setPhase('ordering');
                await sleep(2500);
                if (cancelled) break;

                // Phase 5: Incoming (January inbound shipment scheduled)
                setPhase('incoming');
                await sleep(2000);
                if (cancelled) break;

                // Phase 6: Restocking (Stock goes back up)
                setPhase('restocking');
                await sleep(2000);
            }
        })();

        return () => {
            cancelled = true;
            if (timeoutId) clearTimeout(timeoutId);
        };
    }, []);

    // Dynamic stock value calculation for display
    const getDisplayStock = (item: InventoryItem) => {
        if (item.id !== '2') return item.currentStock; // Only animate Valves A

        switch (phase) {
            case 'monitoring': return 420;
            case 'depleting': return 120; // Dropping
            case 'critical': return 45;   // Below threshold
            case 'ordering': return 45;   // Holding
            case 'incoming': return 45;   // Inbound shipment scheduled
            case 'restocking': return 500; // Full
            default: return 420;
        }
    };

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

                {/* Header Section */}
                <div className="flex justify-between items-start mb-8 z-10">
                    <div>
                        <div className="flex items-center gap-2 mb-1">
                            <div
                                className={`w-2 h-2 rounded-full ${phase === 'critical'
                                    ? 'bg-red-500 animate-ping'
                                    : phase === 'incoming'
                                        ? 'bg-purple-500 animate-pulse'
                                        : 'bg-emerald-500 animate-pulse'
                                    }`}
                            />
                            <h3 className="text-sm font-bold text-slate-800 dark:text-slate-100 uppercase tracking-wider">
                                Inventory Watchdog
                            </h3>
                        </div>
                        <p className="text-xs text-slate-500 font-mono">SYSTEM: ONLINE • LATENCY: 12ms</p>
                    </div>
                    <div className="p-2 bg-white dark:bg-slate-800 rounded-lg shadow-sm border border-slate-200 dark:border-slate-700">
                        <Activity size={16} className="text-slate-400" />
                    </div>
                </div>

                {/* Inventory List */}
                <div className="space-y-4 z-10 flex-1">
                    {items.map((item) => {
                        const isTarget = item.id === '2';
                        const currentStock = getDisplayStock(item);
                        const percent = (currentStock / item.maxStock) * 100;
                        const isCritical = currentStock <= item.threshold;

                        return (
                            <motion.div
                                key={item.id}
                                layout
                                className={`relative p-4 rounded-xl border transition-colors duration-500 ${isTarget && isCritical
                                    ? 'bg-red-50/50 dark:bg-red-900/10 border-red-200 dark:border-red-900/30'
                                    : 'bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700'
                                    }`}
                            >
                                <div className="flex justify-between items-start mb-3">
                                    <div>
                                        <div className="flex items-center gap-2">
                                            <span className="font-semibold text-slate-700 dark:text-slate-200">{item.name}</span>
                                            <span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-700 text-slate-500 font-mono">
                                                {item.sku}
                                            </span>
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <motion.div
                                            className={`text-lg font-bold font-mono ${isCritical ? 'text-red-600 dark:text-red-400' : 'text-slate-700 dark:text-slate-200'
                                                }`}
                                            animate={{ opacity: [1, 0.5, 1] }}
                                            transition={{ duration: 0.5, times: [0, 0.5, 1], repeat: phase === 'depleting' && isTarget ? Infinity : 0 }}
                                        >
                                            {isTarget ? (
                                                <StockCounter value={currentStock} />
                                            ) : currentStock}
                                            <span className="text-xs text-slate-400 ml-1 font-normal">{item.unit}</span>
                                        </motion.div>
                                    </div>
                                </div>

                                {/* Progress Bar */}
                                <div className="h-2 w-full bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden relative">
                                    {/* Threshold Marker */}
                                    <div
                                        className="absolute top-0 bottom-0 w-0.5 bg-red-500/30 z-10"
                                        style={{ left: `${(item.threshold / item.maxStock) * 100}%` }}
                                    />

                                    <motion.div
                                        className={`h-full rounded-full ${isCritical ? 'bg-red-500' : 'bg-blue-500 dark:bg-blue-400'
                                            }`}
                                        initial={{ width: `${percent}%` }}
                                        animate={{ width: `${percent}%` }}
                                        transition={{ duration: phase === 'restocking' ? 1.5 : 0.8, ease: "easeInOut" }}
                                    />
                                </div>

                                {/* Status Indicator */}
                                <div className="mt-2 flex justify-between items-center">
                                    <span className="text-[10px] text-slate-400">Reorder Stock Level: {item.threshold} {item.unit}</span>
                                    {isCritical && (
                                        <motion.div
                                            initial={{ opacity: 0, x: 10 }}
                                            animate={{ opacity: 1, x: 0 }}
                                            className="flex items-center gap-1 text-[10px] font-bold text-red-500 uppercase"
                                        >
                                            <AlertTriangle size={10} />
                                            Stock Breach
                                        </motion.div>
                                    )}
                                </div>
                            </motion.div>
                        );
                    })}
                </div>

                {/* Automation Action Panel */}
                <AnimatePresence>
                    {(phase === 'ordering' || phase === 'incoming' || phase === 'restocking') && (
                        <motion.div
                            initial={{ y: "100%", opacity: 0 }}
                            animate={{ y: 0, opacity: 1 }}
                            exit={{ y: "100%", opacity: 0 }}
                            transition={{ type: "spring", damping: 25, stiffness: 200 }}
                            className="absolute bottom-0 left-0 right-0 bg-white/90 dark:bg-slate-800/90 backdrop-blur-md border-t border-purple-100 dark:border-purple-900/50 p-6 z-20 shadow-[0_-10px_40px_-15px_rgba(0,0,0,0.1)]"
                        >
                            <div className="flex items-start gap-4">
                                <div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-xl text-purple-600 dark:text-purple-400">
                                    {phase === 'restocking' ? (
                                        <CheckCircle2 size={24} />
                                    ) : phase === 'incoming' ? (
                                        <RefreshCw size={24} className="animate-spin" />
                                    ) : (
                                        <Sparkles size={24} />
                                    )}
                                </div>
                                <div className="flex-1">
                                    <h4 className="font-bold text-slate-900 dark:text-white flex items-center gap-2">
                                        {phase === 'restocking'
                                            ? 'Stock Received'
                                            : phase === 'incoming'
                                                ? 'Stock Incoming (January)'
                                                : 'Auto-Reorder Triggered'}
                                        <span className="px-2 py-0.5 rounded-full bg-purple-100 dark:bg-purple-900/50 text-[10px] text-purple-600 dark:text-purple-300 font-mono">
                                            {phase === 'incoming' ? 'INCOMING' : 'AI-AGENT'}
                                        </span>
                                    </h4>

                                    <div className="mt-3 space-y-3">
                                        {/* Step 1: Analysis */}
                                        <div className="flex items-center gap-3 text-xs">
                                            <div className="w-4 h-4 rounded-full bg-green-500 flex items-center justify-center">
                                                <CheckCircle2 size={10} className="text-white" />
                                            </div>
                                            <span className="text-slate-600 dark:text-slate-300">Stock level critical (9%)</span>
                                        </div>

                                        {/* Step 2: Vendor Selection */}
                                        <motion.div
                                            initial={{ opacity: 0, x: -10 }}
                                            animate={{ opacity: 1, x: 0 }}
                                            transition={{ delay: 0.5 }}
                                            className="flex items-center gap-3 text-xs"
                                        >
                                            <div
                                                className={`w-4 h-4 rounded-full flex items-center justify-center ${phase === 'ordering'
                                                    ? 'bg-purple-500 animate-pulse'
                                                    : 'bg-green-500'
                                                    }`}
                                            >
                                                {phase === 'ordering' ? (
                                                    <div className="w-1.5 h-1.5 bg-white rounded-full" />
                                                ) : (
                                                    <CheckCircle2 size={10} className="text-white" />
                                                )}
                                            </div>
                                            <span className="text-slate-600 dark:text-slate-300">
                                                {phase === 'ordering' ? 'Selecting best vendor...' : 'Vendor "Apex Supplies" selected'}
                                            </span>
                                        </motion.div>

                                        {/* Step 3: PO Generation */}
                                        <motion.div
                                            initial={{ opacity: 0, x: -10 }}
                                            animate={{ opacity: 1, x: 0 }}
                                            transition={{ delay: 1.5 }}
                                            className="flex items-center gap-3 text-xs"
                                        >
                                            <div
                                                className={`w-4 h-4 rounded-full flex items-center justify-center ${phase === 'restocking'
                                                    ? 'bg-green-500'
                                                    : phase === 'incoming'
                                                        ? 'bg-purple-500 animate-pulse'
                                                        : 'bg-slate-200 dark:bg-slate-700'
                                                    }`}
                                            >
                                                {phase === 'restocking' ? (
                                                    <CheckCircle2 size={10} className="text-white" />
                                                ) : phase === 'incoming' ? (
                                                    <div className="w-1.5 h-1.5 bg-white rounded-full" />
                                                ) : null}
                                            </div>
                                            <span
                                                className={`${phase === 'restocking' || phase === 'incoming'
                                                    ? 'text-slate-600 dark:text-slate-300'
                                                    : 'text-slate-400'
                                                    }`}
                                            >
                                                {phase === 'incoming' || phase === 'restocking' ? 'PO #9921 generated' : 'Generating PO #9921'}
                                            </span>
                                        </motion.div>

                                        {/* Step 4: Incoming (January) */}
                                        <motion.div
                                            initial={{ opacity: 0, x: -10 }}
                                            animate={{ opacity: 1, x: 0 }}
                                            transition={{ delay: 2.3 }}
                                            className="flex items-center gap-3 text-xs"
                                        >
                                            <div
                                                className={`w-4 h-4 rounded-full flex items-center justify-center ${phase === 'restocking'
                                                    ? 'bg-green-500'
                                                    : phase === 'incoming'
                                                        ? 'bg-purple-500 animate-pulse'
                                                        : 'bg-slate-200 dark:bg-slate-700'
                                                    }`}
                                            >
                                                {phase === 'restocking' ? (
                                                    <CheckCircle2 size={10} className="text-white" />
                                                ) : phase === 'incoming' ? (
                                                    <div className="w-1.5 h-1.5 bg-white rounded-full" />
                                                ) : null}
                                            </div>
                                            <span
                                                className={`${phase === 'restocking' || phase === 'incoming'
                                                    ? 'text-slate-600 dark:text-slate-300'
                                                    : 'text-slate-400'
                                                    }`}
                                            >
                                                {phase === 'incoming' || phase === 'restocking'
                                                    ? `Inbound shipment scheduled: ${incomingDateLabel}`
                                                    : 'Waiting for inbound confirmation...'}
                                            </span>
                                        </motion.div>
                                    </div>

                                    {/* Success Message */}
                                    {phase === 'restocking' && (
                                        <motion.div
                                            initial={{ opacity: 0, y: 10 }}
                                            animate={{ opacity: 1, y: 0 }}
                                            className="mt-4 p-2 bg-green-50 dark:bg-green-900/20 rounded border border-green-100 dark:border-green-900/30 text-xs text-green-700 dark:text-green-400 flex items-center gap-2"
                                        >
                                            <Package size={12} />
                                            <span>Inbound received ({incomingDateLabel}). Stock updated.</span>
                                        </motion.div>
                                    )}
                                </div>
                            </div>
                        </motion.div>
                    )}
                </AnimatePresence>

                {/* Background Elements */}
                <div className="absolute inset-0 bg-[url('https://grainy-gradients.vercel.app/noise.svg')] opacity-20 pointer-events-none mix-blend-overlay" />
                <div className="absolute -top-20 -right-20 w-64 h-64 bg-purple-500/10 rounded-full blur-3xl pointer-events-none" />
                <div className="absolute -bottom-20 -left-20 w-64 h-64 bg-blue-500/10 rounded-full blur-3xl pointer-events-none" />
            </div>
        </CardShell>
    );
};

// Helper component for smooth number counting
const StockCounter = ({ value }: { value: number }) => {
    const [displayValue, setDisplayValue] = useState(value);

    useEffect(() => {
        const controls = {
            value: displayValue,
            stop: false
        };

        const animate = () => {
            if (controls.stop) return;
            const diff = value - controls.value;
            if (Math.abs(diff) < 1) {
                setDisplayValue(value);
                return;
            }
            controls.value += diff * 0.1;
            setDisplayValue(Math.round(controls.value));
            requestAnimationFrame(animate);
        };

        animate();
        return () => { controls.stop = true; };
    }, [value]);

    return <span>{displayValue}</span>;
};
