import React, { useCallback, useEffect, useMemo, useState } from "react";
import { CloudOff, RefreshCw, CheckCircle2, AlertTriangle, Clock, Trash2 } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { toast } from "sonner";
import { listQueue, removeQueueItem } from "@/lib/localdb";
import { runSync } from "@/lib/syncEngine";
import { onFlagsChange, isMutationQueueEnabled } from "@/lib/offlineGate";

/**
 * MutationQueueBadge — visible only when the `mutation-queue` feature flag
 * is enabled for the current user. Surfaces the pending / failed mutations
 * that the offline queue is carrying. Same data the existing /sync surface
 * uses, but next to the header for at-a-glance visibility.
 *
 * Polling is gentle (5s) and only runs while the popover is closed or open;
 * unmounted tabs cost nothing.
 *
 * Color coding:
 *   green  → 0 pending, 0 errored
 *   amber  → ≥1 pending OR last sync >5min ago
 *   rose   → ≥1 errored item (max attempts reached)
 */
const POLL_MS = 5_000;

export function MutationQueueBadge() {
    const [enabled, setEnabled] = useState(() => isMutationQueueEnabled());
    const [items, setItems] = useState([]);
    const [busy, setBusy] = useState(false);

    useEffect(() => {
        return onFlagsChange(() => setEnabled(isMutationQueueEnabled()));
    }, []);

    const refresh = useCallback(async () => {
        try {
            const rows = await listQueue();
            setItems(rows);
        } catch {
            setItems([]);
        }
    }, []);

    useEffect(() => {
        if (!enabled) return;
        refresh();
        const id = setInterval(refresh, POLL_MS);
        const onOnline = () => refresh();
        window.addEventListener("online", onOnline);
        return () => {
            clearInterval(id);
            window.removeEventListener("online", onOnline);
        };
    }, [enabled, refresh]);

    const { pendingCount, errorCount } = useMemo(() => {
        let pending = 0, errored = 0;
        for (const it of items) {
            if (it.status === "error") errored += 1;
            else pending += 1;
        }
        return { pendingCount: pending, errorCount: errored };
    }, [items]);

    if (!enabled) return null;

    const totalCount = pendingCount + errorCount;
    const tone = errorCount > 0
        ? { bg: "bg-rose-100 dark:bg-rose-900/40", text: "text-rose-700 dark:text-rose-200", ring: "ring-rose-500/30" }
        : totalCount > 0
            ? { bg: "bg-amber-100 dark:bg-amber-900/30", text: "text-amber-800 dark:text-amber-200", ring: "ring-amber-500/30" }
            : { bg: "bg-emerald-100 dark:bg-emerald-900/30", text: "text-emerald-700 dark:text-emerald-200", ring: "ring-emerald-500/30" };

    const Icon = errorCount > 0 ? AlertTriangle : totalCount > 0 ? CloudOff : CheckCircle2;

    const handleSync = async () => {
        if (busy) return;
        setBusy(true);
        try {
            const res = await runSync({ silent: false, manual: true });
            if (res?.skipped) {
                toast.info(`Sync skipped (${res.reason || "no connection"})`);
            } else if (res?.synced || res?.pulled) {
                toast.success(`Synced ${res.synced || 0} ops · pulled ${res.pulled || 0} rows`);
            } else {
                toast.info("Sync complete — nothing pending");
            }
            await refresh();
        } catch (e) {
            toast.error("Sync failed — will retry automatically");
        } finally {
            setBusy(false);
        }
    };

    const handleRemove = async (id) => {
        try {
            await removeQueueItem(id);
            await refresh();
            toast.success("Removed from queue");
        } catch {
            toast.error("Could not remove item");
        }
    };

    return (
        <Popover>
            <PopoverTrigger asChild>
                <button
                    type="button"
                    data-testid="mutation-queue-badge"
                    aria-label={`Offline queue: ${totalCount} pending`}
                    className={`relative inline-flex items-center justify-center h-9 w-9 rounded-md ${tone.bg} ${tone.text} hover:ring-2 ${tone.ring} transition`}
                >
                    <Icon className="h-4 w-4" />
                    {totalCount > 0 && (
                        <span
                            className="absolute -top-1.5 -right-1.5 text-[10px] font-bold leading-none px-1.5 py-0.5 rounded-full bg-background border border-border shadow-sm num"
                            data-testid="mutation-queue-count"
                        >
                            {totalCount > 99 ? "99+" : totalCount}
                        </span>
                    )}
                </button>
            </PopoverTrigger>
            <PopoverContent align="end" className="w-[360px] p-0" data-testid="mutation-queue-panel">
                <div className="px-4 pt-3 pb-2 flex items-start justify-between gap-2">
                    <div>
                        <p className="text-xs uppercase tracking-wider text-muted-foreground">Offline queue</p>
                        <h3 className="font-semibold text-sm flex items-center gap-2">
                            <Clock className="w-4 h-4" />
                            {totalCount === 0 ? "All synced" : `${totalCount} mutation${totalCount === 1 ? "" : "s"}`}
                        </h3>
                    </div>
                    <Button
                        size="sm"
                        variant="outline"
                        onClick={handleSync}
                        disabled={busy}
                        data-testid="mutation-queue-sync"
                    >
                        <RefreshCw className={`w-3.5 h-3.5 mr-1 ${busy ? "animate-spin" : ""}`} />
                        Sync now
                    </Button>
                </div>
                <Separator />
                <div className="max-h-72 overflow-y-auto" data-testid="mutation-queue-list">
                    {totalCount === 0 ? (
                        <div className="px-4 py-6 text-center">
                            <CheckCircle2 className="w-8 h-8 mx-auto text-emerald-500 mb-2" />
                            <p className="text-sm text-muted-foreground">Nothing pending. All offline writes have been synced.</p>
                        </div>
                    ) : (
                        <ul className="divide-y divide-border">
                            {items.map((it) => {
                                const p = it.payload || {};
                                const isErr = it.status === "error";
                                return (
                                    <li
                                        key={it._id}
                                        className="px-4 py-2.5 flex items-start gap-2"
                                        data-testid={`mutation-queue-item-${it._id}`}
                                    >
                                        <div className="flex-1 min-w-0">
                                            <div className="text-sm font-medium truncate">{p.summary || `${p.method || "POST"} ${p.url || it.kind}`}</div>
                                            <div className="text-[11px] text-muted-foreground flex items-center gap-2 mt-0.5">
                                                <Badge variant={isErr ? "destructive" : "outline"} className="text-[10px] font-mono px-1.5 py-0">
                                                    {it.kind || "op"}
                                                </Badge>
                                                <span>attempts: {it.attempts || 0}</span>
                                                {it.lastError && <span className="text-rose-500 truncate" title={it.lastError}>· {String(it.lastError).slice(0, 40)}</span>}
                                            </div>
                                        </div>
                                        <button
                                            onClick={() => handleRemove(it._id)}
                                            className="p-1 rounded hover:bg-rose-100 dark:hover:bg-rose-900/30 text-rose-500"
                                            aria-label="Remove from queue"
                                            data-testid={`mutation-queue-remove-${it._id}`}
                                        >
                                            <Trash2 className="w-3.5 h-3.5" />
                                        </button>
                                    </li>
                                );
                            })}
                        </ul>
                    )}
                </div>
                <Separator />
                <div className="px-4 py-2 text-[10px] text-muted-foreground">
                    Items auto-sync when you come back online. Failed items retry up to 5 times.
                </div>
            </PopoverContent>
        </Popover>
    );
}
