import React, { useEffect, useState, useCallback, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Bell, AlertTriangle, Package, Receipt, FileBarChart, Check, CheckCheck } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import {
    Popover, PopoverContent, PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import { useCompany } from "@/context/CompanyContext";
import { formatINR } from "@/lib/format";
import { cn } from "@/lib/utils";

const SEV_META = {
    danger: { icon: Receipt, color: "text-rose-600 dark:text-rose-400", ring: "ring-rose-500/40", bg: "bg-rose-500/10" },
    warning: { icon: AlertTriangle, color: "text-amber-600 dark:text-amber-400", ring: "ring-amber-500/40", bg: "bg-amber-500/10" },
    info: { icon: FileBarChart, color: "text-blue-600 dark:text-blue-400", ring: "ring-blue-500/40", bg: "bg-blue-500/10" },
};

const TYPE_ICON = {
    low_stock: Package,
    overdue: Receipt,
    cheque_pending: FileBarChart,
    gst_reminder: AlertTriangle,
};

export function NotificationsBell() {
    const { activeId } = useCompany();
    const navigate = useNavigate();
    const [open, setOpen] = useState(false);
    const [items, setItems] = useState([]);
    const [count, setCount] = useState(0);
    const [loading, setLoading] = useState(false);
    const pollRef = useRef(null);

    const fetchCount = useCallback(async () => {
        if (!activeId) return;
        try {
            const { data } = await api.get("/notifications/unread-count", { params: { company_id: activeId } });
            setCount(data.count || 0);
        } catch { /* noop */ }
    }, [activeId]);

    const fetchList = useCallback(async () => {
        if (!activeId) return;
        setLoading(true);
        try {
            const { data } = await api.get("/notifications", { params: { company_id: activeId } });
            setItems(data || []);
        } finally { setLoading(false); }
    }, [activeId]);

    // Poll unread count every 60s
    useEffect(() => {
        fetchCount();
        pollRef.current = setInterval(fetchCount, 60000);
        return () => clearInterval(pollRef.current);
    }, [fetchCount]);

    useEffect(() => {
        if (open) fetchList();
    }, [open, fetchList]);

    const markRead = async (id) => {
        try {
            await api.post(`/notifications/${encodeURIComponent(id)}/read`);
            setItems((arr) => arr.map((n) => (n.id === id ? { ...n, read: true } : n)));
            fetchCount();
        } catch { /* noop */ }
    };

    const markAllRead = async () => {
        try {
            await api.post("/notifications/read-all", null, { params: { company_id: activeId } });
            setItems((arr) => arr.map((n) => ({ ...n, read: true })));
            setCount(0);
        } catch { /* noop */ }
    };

    const open_ = (n) => {
        markRead(n.id);
        if (n.link) navigate(n.link);
        setOpen(false);
    };

    const unread = items.filter((n) => !n.read);

    return (
        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <button
                    className="relative p-2 rounded-md hover:bg-muted transition-colors"
                    aria-label="Notifications"
                    data-testid="notifications-bell"
                    title={`${count} unread notification${count === 1 ? "" : "s"}`}
                >
                    <Bell className="h-4 w-4" />
                    {count > 0 && (
                        <Badge
                            className="absolute -top-0.5 -right-0.5 h-4 min-w-[16px] px-1 text-[9px] font-bold bg-rose-500 hover:bg-rose-500 text-white border-2 border-background"
                            data-testid="notifications-badge"
                        >
                            {count > 99 ? "99+" : count}
                        </Badge>
                    )}
                </button>
            </PopoverTrigger>
            <PopoverContent className="w-96 p-0" align="end" data-testid="notifications-popover">
                <div className="flex items-center justify-between px-3 py-2.5 border-b">
                    <div className="font-display text-sm font-semibold flex items-center gap-1.5">
                        <Bell className="h-3.5 w-3.5" /> Notifications
                        {unread.length > 0 && <Badge variant="secondary" className="text-[10px] h-4">{unread.length} new</Badge>}
                    </div>
                    {unread.length > 0 && (
                        <Button variant="ghost" size="sm" onClick={markAllRead} data-testid="notifications-mark-all" className="h-7 text-xs">
                            <CheckCheck className="h-3 w-3 mr-1" /> Mark all read
                        </Button>
                    )}
                </div>
                <div className="max-h-[420px] overflow-y-auto">
                    {loading ? (
                        <div className="p-6 text-center text-xs text-muted-foreground">Loading…</div>
                    ) : items.length === 0 ? (
                        <div className="p-8 text-center text-sm text-muted-foreground">
                            <Bell className="h-6 w-6 mx-auto opacity-40 mb-2" />
                            <div>All caught up 🎉</div>
                            <div className="text-[10px] mt-1">No active alerts right now</div>
                        </div>
                    ) : (
                        items.slice(0, 30).map((n) => {
                            const sev = SEV_META[n.severity] || SEV_META.info;
                            const TIcon = TYPE_ICON[n.type] || sev.icon;
                            return (
                                <button
                                    key={n.id}
                                    onClick={() => open_(n)}
                                    className={cn(
                                        "w-full text-left px-3 py-2.5 border-b last:border-b-0 flex items-start gap-3 hover:bg-muted/40 transition-colors",
                                        !n.read && "bg-primary/5"
                                    )}
                                    data-testid={`notification-${n.id}`}
                                >
                                    <span className={cn("h-7 w-7 rounded-md inline-flex items-center justify-center flex-shrink-0", sev.bg, sev.color)}>
                                        <TIcon className="h-3.5 w-3.5" />
                                    </span>
                                    <div className="flex-1 min-w-0">
                                        <div className="text-xs font-medium truncate flex items-center gap-1.5">
                                            {!n.read && <span className="h-1.5 w-1.5 rounded-full bg-primary flex-shrink-0" />}
                                            {n.title}
                                        </div>
                                        <div className="text-[11px] text-muted-foreground truncate mt-0.5">{n.body}</div>
                                    </div>
                                    {!n.read && (
                                        <Check
                                            className="h-3.5 w-3.5 text-muted-foreground hover:text-primary flex-shrink-0 mt-1"
                                            onClick={(e) => { e.stopPropagation(); markRead(n.id); }}
                                            data-testid={`notification-mark-read-${n.id}`}
                                        />
                                    )}
                                </button>
                            );
                        })
                    )}
                </div>
                <div className="border-t px-3 py-2 text-[10px] text-muted-foreground flex items-center justify-between">
                    <span>Auto-refresh every minute</span>
                    <button onClick={() => { navigate("/notifications"); setOpen(false); }} className="text-primary hover:underline" data-testid="notifications-see-all">
                        See all →
                    </button>
                </div>
            </PopoverContent>
        </Popover>
    );
}
