'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { CheckCircle2, FileText, Mail, Package, Send, ShieldCheck } from 'lucide-react';
import { CardShell } from '../shared/CardShell';

type NotificationChannel = 'message' | 'email';
type NotificationKind = 'info' | 'success';

type Notification = {
    id: string;
    channel: NotificationChannel;
    kind: NotificationKind;
    title: string;
    body: string;
};

export const DispatchVisual = () => {
    const sequence = useMemo<Notification[]>(
        () => [
            {
                id: 'order-received',
                channel: 'message',
                kind: 'info',
                title: 'Order received',
                body: 'Thanks — we’ve got it. We’ll keep you updated at each milestone.'
            },
            {
                id: 'processing',
                channel: 'message',
                kind: 'info',
                title: 'Processing started',
                body: 'Items are being picked and prepared for dispatch.'
            },
            {
                id: 'invoice-generated',
                channel: 'email',
                kind: 'info',
                title: 'Invoice created',
                body: 'Invoice #INV-1042 is ready. A copy has been sent to your email.'
            },
            {
                id: 'payment-confirmed',
                channel: 'email',
                kind: 'success',
                title: 'Payment confirmed',
                body: 'Payment received. Dispatch is now scheduled.'
            },
            {
                id: 'dispatch-confirmed',
                channel: 'message',
                kind: 'info',
                title: 'Dispatch scheduled',
                body: 'Your order is queued for dispatch. You’ll get a confirmation when it leaves.'
            },
            {
                id: 'dispatched',
                channel: 'message',
                kind: 'success',
                title: 'Dispatched',
                body: 'Your package has been dispatched. No live tracking needed — we’ll notify you proactively.'
            }
        ],
        []
    );

    const [activeIndex, setActiveIndex] = useState(0);

    useEffect(() => {
        const nextDelayMs = activeIndex === 0 ? 900 : 1300;
        const isLast = activeIndex >= sequence.length - 1;

        const t = window.setTimeout(() => {
            if (isLast) {
                // Small pause, then loop.
                setActiveIndex(0);
                return;
            }
            setActiveIndex(i => Math.min(i + 1, sequence.length - 1));
        }, isLast ? 1600 : nextDelayMs);

        return () => window.clearTimeout(t);
    }, [activeIndex, sequence.length]);

    const visible = sequence.slice(0, activeIndex + 1);
    const doneCount = activeIndex;
    const totalCount = sequence.length;

    return (
        <CardShell>
            <div className="h-[600px] relative bg-slate-50 dark:bg-slate-900 overflow-hidden flex flex-col">
                {/* Subtle background */}
                <div className="absolute inset-0 pointer-events-none">
                    <div
                        className="absolute inset-0 opacity-[0.12] dark:opacity-[0.08]"
                        style={{
                            backgroundImage:
                                'radial-gradient(circle at 20% 10%, rgba(59,130,246,0.18), transparent 40%), radial-gradient(circle at 80% 90%, rgba(34,197,94,0.14), transparent 45%)'
                        }}
                    />
                    <motion.div
                        className="absolute -top-16 -left-16 w-72 h-72 rounded-full bg-blue-500/10 blur-3xl"
                        animate={{ x: [0, 24, 0], y: [0, 18, 0] }}
                        transition={{ duration: 6, repeat: Infinity, ease: 'easeInOut' }}
                    />
                    <motion.div
                        className="absolute -bottom-20 -right-20 w-80 h-80 rounded-full bg-emerald-500/10 blur-3xl"
                        animate={{ x: [0, -22, 0], y: [0, -14, 0] }}
                        transition={{ duration: 7, repeat: Infinity, ease: 'easeInOut' }}
                    />
                </div>

                <div className="relative z-10 flex flex-col h-full p-4">
                    {/* Header */}
                    <div className="flex items-start justify-between gap-4">
                        <div className="min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                                <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                                <h3 className="text-sm font-bold text-slate-800 dark:text-slate-100 uppercase tracking-wider">
                                    Status notifications
                                </h3>
                            </div>
                            <p className="text-xs text-slate-600 dark:text-slate-300">
                                Messages + email updates, sent automatically — no live tracking required.
                            </p>
                        </div>

                        <div className="shrink-0 flex items-center gap-2 rounded-xl border border-slate-200 dark:border-slate-700 bg-white/70 dark:bg-slate-800/60 backdrop-blur px-3 py-2">
                            <div className="flex items-center gap-2 text-slate-600 dark:text-slate-300">
                                <Package size={16} />
                                <span className="text-xs font-mono">#ORD-882</span>
                            </div>
                        </div>
                    </div>

                    {/* Body */}
                    <div className="mt-3 grid grid-cols-12 gap-3 flex-1 min-h-0">
                        {/* Left: milestone stack */}
                        <div className="col-span-4 min-h-0">
                            <div className="h-full rounded-2xl border border-slate-200 dark:border-slate-700 bg-white/70 dark:bg-slate-800/60 backdrop-blur p-3 flex flex-col">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                        <ShieldCheck className="text-emerald-600 dark:text-emerald-400" size={18} />
                                        <div className="text-xs font-bold text-slate-700 dark:text-slate-200">
                                            Comfort timeline
                                        </div>
                                    </div>
                                    <div className="text-[10px] font-mono text-slate-500 dark:text-slate-400">
                                        {Math.min(doneCount + 1, totalCount)}/{totalCount}
                                    </div>
                                </div>

                                <div className="mt-3 space-y-2">
                                    {sequence.map((n, idx) => (
                                        <MilestoneRow
                                            key={n.id}
                                            label={n.title}
                                            state={idx < activeIndex ? 'done' : idx === activeIndex ? 'active' : 'upcoming'}
                                        />
                                    ))}
                                </div>

                                <div className="mt-auto pt-3">
                                    <div className="text-[11px] leading-snug text-slate-600 dark:text-slate-300">
                                        Confirmations at each step: processing → invoicing → dispatch.
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Right: notification feed */}
                        <div className="col-span-8 min-h-0">
                            <div className="h-full rounded-2xl border border-slate-200 dark:border-slate-700 bg-white/70 dark:bg-slate-800/60 backdrop-blur p-3 flex flex-col min-h-0">
                                <div className="flex items-center justify-between gap-3">
                                    <div className="flex items-center gap-2 min-w-0">
                                        <Send className="text-blue-600 dark:text-blue-400" size={18} />
                                        <div className="text-xs font-bold text-slate-700 dark:text-slate-200 truncate">
                                            Notification feed
                                        </div>
                                    </div>
                                    <div className="text-[10px] text-slate-500 dark:text-slate-400 font-mono">
                                        auto-send: ON
                                    </div>
                                </div>

                                <div className="mt-2 flex-1 min-h-0 overflow-hidden">
                                    <div className="h-full overflow-y-auto pr-1 space-y-2">
                                        <AnimatePresence initial={false}>
                                            {visible.map((n, idx) => (
                                                <NotificationCard
                                                    key={n.id}
                                                    notification={n}
                                                    isNewest={idx === visible.length - 1}
                                                />
                                            ))}
                                        </AnimatePresence>
                                    </div>
                                </div>

                                <div className="mt-2 pt-2 border-t border-slate-200/70 dark:border-slate-700/70 flex items-center justify-between">
                                    <div className="text-[11px] text-slate-600 dark:text-slate-300">
                                        We notify you proactively — fewer check-ins, more confidence.
                                    </div>
                                    <div className="flex items-center gap-2 text-[11px] text-slate-600 dark:text-slate-300">
                                        <CheckCircle2 className="text-emerald-600 dark:text-emerald-400" size={14} />
                                        <span>All milestones covered</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </CardShell>
    );
};

function MilestoneRow({
    label,
    state
}: {
    label: string;
    state: 'done' | 'active' | 'upcoming';
}) {
    const dot =
        state === 'done'
            ? 'bg-emerald-500'
            : state === 'active'
              ? 'bg-blue-500 animate-pulse'
              : 'bg-slate-300 dark:bg-slate-600';

    const text =
        state === 'done'
            ? 'text-slate-700 dark:text-slate-200'
            : state === 'active'
              ? 'text-blue-700 dark:text-blue-200'
              : 'text-slate-500 dark:text-slate-400';

    const bg =
        state === 'active'
            ? 'bg-blue-50/80 dark:bg-blue-900/20 border-blue-200/70 dark:border-blue-700/40'
            : 'bg-transparent border-transparent';

    return (
        <div className={`flex items-center gap-2 rounded-lg border px-2 py-1.5 ${bg}`}>
            <div className={`w-2.5 h-2.5 rounded-full ${dot}`} />
            <div className={`text-[11px] leading-snug font-semibold ${text}`}>{label}</div>
        </div>
    );
}

function NotificationCard({
    notification,
    isNewest
}: {
    notification: Notification;
    isNewest: boolean;
}) {
    const isEmail = notification.channel === 'email';
    const isSuccess = notification.kind === 'success';

    const icon = isEmail ? Mail : isSuccess ? CheckCircle2 : FileText;

    const tint = isSuccess
        ? 'border-emerald-200/80 dark:border-emerald-700/40 bg-emerald-50/70 dark:bg-emerald-900/15'
        : isEmail
          ? 'border-indigo-200/80 dark:border-indigo-700/40 bg-indigo-50/70 dark:bg-indigo-900/15'
          : 'border-slate-200/80 dark:border-slate-700/50 bg-white/70 dark:bg-slate-900/25';

    const label = isEmail ? 'Email' : 'Message';

    const Icon = icon;

    return (
        <motion.div
            initial={{ y: 10, opacity: 0, scale: 0.98 }}
            animate={{ y: 0, opacity: 1, scale: 1 }}
            exit={{ y: -10, opacity: 0, scale: 0.98 }}
            transition={{ type: 'spring', stiffness: 420, damping: 30 }}
            className={`rounded-2xl border p-2.5 backdrop-blur ${tint}`}
        >
            <div className="flex items-start justify-between gap-3">
                <div className="flex items-start gap-2 min-w-0">
                    <div
                        className={`mt-0.5 w-7 h-7 rounded-xl flex items-center justify-center ${
                            isSuccess
                                ? 'bg-emerald-600 text-white'
                                : isEmail
                                  ? 'bg-indigo-600 text-white'
                                  : 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900'
                        }`}
                    >
                        <Icon size={14} />
                    </div>
                    <div className="min-w-0">
                        <div className="flex items-center gap-2">
                            <div className="text-xs font-bold text-slate-800 dark:text-slate-100 truncate">
                                {notification.title}
                            </div>
                            {isNewest && (
                                <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-blue-600 text-white">
                                    new
                                </span>
                            )}
                        </div>
                        <div className="mt-0.5 text-xs leading-snug text-slate-700 dark:text-slate-200">
                            {notification.body}
                        </div>
                    </div>
                </div>

                <div className="shrink-0 flex flex-col items-end">
                    <span className="text-[10px] font-semibold text-slate-500 dark:text-slate-400">{label}</span>
                    <span className="text-[10px] font-mono text-slate-400 dark:text-slate-500">just now</span>
                </div>
            </div>
        </motion.div>
    );
}