/**
 * Agent Dashboard — Conversations view (wrapped by DashboardLayout)
 * Redesigned for large-volume conversation management with
 * search, filters (status, agent, date), pagination, sorting, and bulk actions.
 */
import { useState, useRef, useEffect, useMemo, useCallback } from "react";
import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  MessageSquare, CheckCircle2, AlertTriangle, Clock,
  Send, Bot, User, Headphones, ArrowLeft, ArrowUpDown,
  BarChart3, X, Search, Filter, ChevronLeft, ChevronRight,
  Calendar, UserCheck, Trash2, MoreHorizontal, MessageCircle,
  Sparkles, Bell, BellRing,
} from "lucide-react";
import { Streamdown } from "streamdown";
import { toast } from "sonner";

/* ─── Bot name constant ─── */
const BOT_NAME = "Ellie";

/* ─── Status badge colors ─── */
const STATUS_STYLES: Record<string, { bg: string; text: string; label: string; dot: string }> = {
  active: { bg: "#14532D12", text: "#14532D", label: "Active", dot: "#22c55e" },
  escalated: { bg: "#C2410C12", text: "#C2410C", label: "Escalated", dot: "#f97316" },
  resolved: { bg: "#0369a112", text: "#0369a1", label: "Resolved", dot: "#3b82f6" },
  closed: { bg: "#78716C12", text: "#78716C", label: "Closed", dot: "#a8a29e" },
};

/* ─── Stats Card ─── */
function StatCard({ icon, label, value, color, isActive, onClick }: {
  icon: React.ReactNode; label: string; value: number; color: string;
  isActive?: boolean; onClick?: () => void;
}) {
  return (
    <button
      onClick={onClick}
      className="p-3 rounded-xl border transition-all text-left w-full"
      style={{
        background: isActive ? color + "08" : "#fff",
        borderColor: isActive ? color + "40" : "#e7e0d5",
        boxShadow: isActive ? `0 0 0 1px ${color}20` : undefined,
      }}
    >
      <div className="flex items-center gap-2.5">
        <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ background: color + "14", color }}>
          {icon}
        </div>
        <div>
          <div className="text-xl font-bold" style={{ color: "#292524", fontFamily: "'Playfair Display', serif" }}>{value}</div>
          <div className="text-[11px]" style={{ color: "#a8a29e", fontFamily: "'Source Sans 3', sans-serif" }}>{label}</div>
        </div>
      </div>
    </button>
  );
}

/* ─── Conversation Row (table-style for large volumes) ─── */
function ConversationRow({
  conversation,
  isSelected,
  isChecked,
  onClick,
  onCheck,
}: {
  conversation: any;
  isSelected: boolean;
  isChecked: boolean;
  onClick: () => void;
  onCheck: (checked: boolean) => void;
}) {
  const style = STATUS_STYLES[conversation.status] || STATUS_STYLES.active;
  const createdDate = new Date(conversation.createdAt);
  const updatedDate = new Date(conversation.updatedAt);
  const isToday = new Date().toDateString() === updatedDate.toDateString();

  return (
    <div
      className="flex items-center gap-3 px-3 py-2.5 border-b transition-all cursor-pointer hover:bg-stone-50"
      style={{
        background: isSelected ? "#14532D06" : isChecked ? "#fef3c7" : "transparent",
        borderColor: "#f5f0e8",
      }}
    >
      {/* Checkbox */}
      <input
        type="checkbox"
        checked={isChecked}
        onChange={(e) => { e.stopPropagation(); onCheck(e.target.checked); }}
        className="w-4 h-4 rounded border-stone-300 accent-green-800 shrink-0"
      />

      {/* Main content — clickable */}
      <div className="flex-1 min-w-0 flex items-center gap-3" onClick={onClick}>
        {/* Status dot + visitor */}
        <div className="flex items-center gap-2 min-w-0 w-36 shrink-0">
          <div className="w-2 h-2 rounded-full shrink-0" style={{ background: style.dot }} />
          <span className="text-sm font-medium truncate" style={{ color: "#292524", fontFamily: "'Source Sans 3', sans-serif" }}>
            {conversation.visitorName || "Visitor"}
          </span>
        </div>

        {/* Customer ID */}
        <div className="w-28 shrink-0 hidden lg:block">
          <span className="text-xs font-mono truncate block" style={{ color: conversation.customerId ? "#14532D" : "#d6d3d1" }}>
            {conversation.customerId || "—"}
          </span>
        </div>

        {/* Sales Rep */}
        <div className="w-28 shrink-0 hidden lg:block">
          <span className="text-xs truncate block" style={{ color: conversation.salesRep ? "#78716C" : "#d6d3d1" }}>
            {conversation.salesRep || "—"}
          </span>
        </div>

        {/* Agent Name */}
        <div className="w-28 shrink-0 hidden lg:block">
          <span className="text-xs truncate block" style={{ color: conversation.agentName ? "#0369a1" : "#d6d3d1" }}>
            {conversation.agentName || "—"}
          </span>
        </div>

        {/* Status badge */}
        <div className="w-24 shrink-0">
          <span
            className="text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wider"
            style={{ background: style.bg, color: style.text }}
          >
            {style.label}
          </span>
        </div>

        {/* Message count */}
        <div className="w-14 shrink-0 flex items-center gap-1">
          <MessageCircle className="w-3 h-3" style={{ color: "#a8a29e" }} />
          <span className="text-xs" style={{ color: "#78716C" }}>{conversation.messageCount || 0}</span>
        </div>

        {/* Email / session */}
        <div className="flex-1 min-w-0 hidden xl:block">
          <span className="text-xs truncate block" style={{ color: "#a8a29e" }}>
            {conversation.visitorEmail || `#${conversation.sessionId?.slice(0, 10)}`}
          </span>
        </div>

        {/* Date */}
        <div className="w-28 shrink-0 text-right hidden md:block">
          <span className="text-xs" style={{ color: "#78716C" }}>
            {isToday
              ? updatedDate.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
              : updatedDate.toLocaleDateString([], { month: "short", day: "numeric" })}
          </span>
        </div>
      </div>
    </div>
  );
}

/* ─── Message Bubble ─── */
function MessageBubble({ message }: { message: any }) {
  const isVisitor = message.sender === "visitor";
  const isBot = message.sender === "bot";

  return (
    <div className={`flex gap-2 ${isVisitor ? "justify-end" : "justify-start"}`}>
      {!isVisitor && (
        <div
          className="w-7 h-7 rounded-full flex items-center justify-center shrink-0 mt-1"
          style={{ background: isBot ? "#14532D" : "#C2410C", color: "#fff" }}
        >
          {isBot ? <Sparkles className="w-3.5 h-3.5" /> : <Headphones className="w-3.5 h-3.5" />}
        </div>
      )}
      <div
        className="max-w-[75%] px-3.5 py-2.5 rounded-xl text-sm leading-relaxed"
        style={{
          background: isVisitor ? "#14532D" : "#f5f0e8",
          color: isVisitor ? "#fff" : "#292524",
          fontFamily: "'Source Sans 3', sans-serif",
          borderBottomRightRadius: isVisitor ? "4px" : undefined,
          borderBottomLeftRadius: !isVisitor ? "4px" : undefined,
        }}
      >
        {!isVisitor && (
          <div className="text-[10px] font-semibold mb-1" style={{ color: isBot ? "#14532D" : "#C2410C" }}>
            {isBot ? BOT_NAME : (message.metadata?.agentName || "Agent")}
          </div>
        )}
        {!isVisitor ? (
          <div className="prose prose-sm max-w-none" style={{ color: "inherit" }}>
            <Streamdown>{message.content}</Streamdown>
          </div>
        ) : (
          message.content
        )}
        <div className="text-[10px] mt-1 opacity-60">
          {new Date(message.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
        </div>
      </div>
      {isVisitor && (
        <div className="w-7 h-7 rounded-full flex items-center justify-center shrink-0 mt-1" style={{ background: "#78716C20", color: "#78716C" }}>
          <User className="w-3.5 h-3.5" />
        </div>
      )}
    </div>
  );
}

/* ─── Chat Panel ─── */
function ChatPanel({
  conversationId,
  conversation,
  onBack,
}: {
  conversationId: number;
  conversation: any;
  onBack: () => void;
}) {
  const [replyText, setReplyText] = useState("");
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const utils = trpc.useUtils();

  const { data: messagesData, isLoading } = trpc.agent.messages.useQuery(
    { conversationId },
    { refetchInterval: 3000 }
  );

  const replyMutation = trpc.agent.reply.useMutation({
    onSuccess: () => {
      setReplyText("");
      utils.agent.messages.invalidate({ conversationId });
      utils.agent.conversationsAdvanced.invalidate();
    },
  });

  const statusMutation = trpc.agent.updateStatus.useMutation({
    onSuccess: () => {
      utils.agent.conversationsAdvanced.invalidate();
      utils.agent.stats.invalidate();
    },
  });

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messagesData]);

  const handleSend = () => {
    if (!replyText.trim()) return;
    replyMutation.mutate({ conversationId, content: replyText.trim() });
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const style = STATUS_STYLES[conversation?.status] || STATUS_STYLES.active;

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: "#e7e0d5" }}>
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="p-1.5 rounded-lg hover:bg-black/5 transition-colors">
            <ArrowLeft className="w-4 h-4" style={{ color: "#78716C" }} />
          </button>
          <div>
            <div className="flex items-center gap-2">
              <span className="text-sm font-bold" style={{ color: "#292524", fontFamily: "'Source Sans 3', sans-serif" }}>
                {conversation?.visitorName || "Visitor"}
              </span>
              <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wider" style={{ background: style.bg, color: style.text }}>
                {style.label}
              </span>
            </div>
            <div className="flex items-center gap-3 flex-wrap">
              <span className="text-xs" style={{ color: "#a8a29e" }}>
                {conversation?.visitorEmail || `Session: ${conversation?.sessionId?.slice(0, 12)}`}
                {conversation?.assignedAgentId && " · Assigned"}
              </span>
              {conversation?.customerId && (
                <span className="text-xs font-mono px-1.5 py-0.5 rounded" style={{ background: "#14532D0a", color: "#14532D" }}>
                  ID: {conversation.customerId}
                </span>
              )}
              {conversation?.salesRep && (
                <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: "#C2410C0a", color: "#C2410C" }}>
                  Rep: {conversation.salesRep}
                </span>
              )}
              {conversation?.agentName && (
                <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: "#0369a10a", color: "#0369a1" }}>
                  Agent: {conversation.agentName}
                </span>
              )}
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {conversation?.status !== "resolved" && (
            <Button
              size="sm" variant="outline"
              onClick={() => statusMutation.mutate({ conversationId, status: "resolved" })}
              className="text-xs" style={{ borderColor: "#14532D40", color: "#14532D" }}
            >
              <CheckCircle2 className="w-3 h-3 mr-1" /> Resolve
            </Button>
          )}
          {conversation?.status !== "closed" && (
            <Button
              size="sm" variant="outline"
              onClick={() => statusMutation.mutate({ conversationId, status: "closed" })}
              className="text-xs" style={{ borderColor: "#78716C40", color: "#78716C" }}
            >
              <X className="w-3 h-3 mr-1" /> Close
            </Button>
          )}
        </div>
      </div>

      {/* Messages */}
      <ScrollArea className="flex-1 p-4">
        <div className="space-y-3">
          {isLoading ? (
            <div className="text-center py-8 text-sm" style={{ color: "#a8a29e" }}>Loading messages...</div>
          ) : (
            messagesData?.map((msg: any) => <MessageBubble key={msg.id} message={msg} />)
          )}
          <div ref={messagesEndRef} />
        </div>
      </ScrollArea>

      {/* Reply input */}
      {conversation?.status !== "closed" && (
        <div className="p-4 border-t" style={{ borderColor: "#e7e0d5" }}>
          <div className="flex gap-2">
            <Textarea
              value={replyText}
              onChange={(e) => setReplyText(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="Type your reply... (Enter to send, Shift+Enter for new line)"
              className="resize-none text-sm"
              rows={2}
              style={{ borderColor: "#e7e0d5", fontFamily: "'Source Sans 3', sans-serif" }}
            />
            <Button
              onClick={handleSend}
              disabled={!replyText.trim() || replyMutation.isPending}
              className="self-end text-white"
              style={{ background: "#14532D" }}
            >
              <Send className="w-4 h-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ─── Pagination Controls ─── */
function PaginationBar({
  page, totalPages, total, pageSize, onPageChange,
}: {
  page: number; totalPages: number; total: number; pageSize: number;
  onPageChange: (p: number) => void;
}) {
  const startItem = (page - 1) * pageSize + 1;
  const endItem = Math.min(page * pageSize, total);

  // Generate page numbers to show
  const pages: (number | "...")[] = [];
  if (totalPages <= 7) {
    for (let i = 1; i <= totalPages; i++) pages.push(i);
  } else {
    pages.push(1);
    if (page > 3) pages.push("...");
    for (let i = Math.max(2, page - 1); i <= Math.min(totalPages - 1, page + 1); i++) {
      pages.push(i);
    }
    if (page < totalPages - 2) pages.push("...");
    pages.push(totalPages);
  }

  return (
    <div className="flex items-center justify-between px-3 py-2.5 border-t" style={{ borderColor: "#e7e0d5" }}>
      <span className="text-xs" style={{ color: "#a8a29e", fontFamily: "'Source Sans 3', sans-serif" }}>
        Showing {startItem}–{endItem} of {total} conversations
      </span>
      <div className="flex items-center gap-1">
        <button
          onClick={() => onPageChange(page - 1)}
          disabled={page <= 1}
          className="w-7 h-7 rounded flex items-center justify-center disabled:opacity-30 hover:bg-stone-100 transition-colors"
        >
          <ChevronLeft className="w-4 h-4" style={{ color: "#78716C" }} />
        </button>
        {pages.map((p, i) =>
          p === "..." ? (
            <span key={`e${i}`} className="w-7 h-7 flex items-center justify-center text-xs" style={{ color: "#a8a29e" }}>...</span>
          ) : (
            <button
              key={p}
              onClick={() => onPageChange(p)}
              className="w-7 h-7 rounded text-xs font-medium flex items-center justify-center transition-colors"
              style={{
                background: p === page ? "#14532D" : "transparent",
                color: p === page ? "#fff" : "#78716C",
              }}
            >
              {p}
            </button>
          )
        )}
        <button
          onClick={() => onPageChange(page + 1)}
          disabled={page >= totalPages}
          className="w-7 h-7 rounded flex items-center justify-center disabled:opacity-30 hover:bg-stone-100 transition-colors"
        >
          <ChevronRight className="w-4 h-4" style={{ color: "#78716C" }} />
        </button>
      </div>
    </div>
  );
}

/* ─── Main Conversations View ─── */
export default function AgentDashboard() {
  const { user, isAuthenticated } = useAuth();
  const utils = trpc.useUtils();

  // Filters state
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [statusFilter, setStatusFilter] = useState<string | undefined>(undefined);
  const [searchQuery, setSearchQuery] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [agentFilter, setAgentFilter] = useState<number | undefined>(undefined);
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");
  const [sortBy, setSortBy] = useState<"updated" | "created" | "visitor" | "status" | "customerId" | "salesRep" | "agent">("updated");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [showFilters, setShowFilters] = useState(false);

  // Selection state
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  const [selectedConversationId, setSelectedConversationId] = useState<number | null>(null);

  // Notification state
  const [notificationsEnabled, setNotificationsEnabled] = useState(false);
  const [prevMessageCounts, setPrevMessageCounts] = useState<Record<number, number>>({});
  const [notificationPermission, setNotificationPermission] = useState<NotificationPermission>(
    typeof window !== "undefined" && "Notification" in window ? Notification.permission : "default"
  );

  // Request browser notification permission
  const requestNotificationPermission = useCallback(async () => {
    if (!("Notification" in window)) {
      toast.error("Browser notifications are not supported");
      return;
    }
    const permission = await Notification.requestPermission();
    setNotificationPermission(permission);
    if (permission === "granted") {
      setNotificationsEnabled(true);
      toast.success("Notifications enabled", { description: "You'll be notified when customers send new messages" });
    } else if (permission === "denied") {
      toast.error("Notifications blocked", { description: "Please enable notifications in your browser settings" });
    }
  }, []);

  // Toggle notifications
  const toggleNotifications = useCallback(() => {
    if (notificationsEnabled) {
      setNotificationsEnabled(false);
      toast.info("Notifications paused");
    } else {
      if (notificationPermission === "granted") {
        setNotificationsEnabled(true);
        toast.success("Notifications enabled");
      } else {
        requestNotificationPermission();
      }
    }
  }, [notificationsEnabled, notificationPermission, requestNotificationPermission]);

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchQuery);
      setPage(1);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  // Reset page when filters change
  useEffect(() => { setPage(1); }, [statusFilter, agentFilter, dateFrom, dateTo, sortBy, sortOrder]);

  // Stabilize query input
  const queryInput = useMemo(() => ({
    page,
    pageSize,
    status: statusFilter,
    search: debouncedSearch || undefined,
    agentId: agentFilter,
    dateFrom: dateFrom || undefined,
    dateTo: dateTo || undefined,
    sortBy,
    sortOrder,
  }), [page, pageSize, statusFilter, debouncedSearch, agentFilter, dateFrom, dateTo, sortBy, sortOrder]);

  const { data: stats } = trpc.agent.stats.useQuery(undefined, {
    refetchInterval: 10000,
    enabled: isAuthenticated,
  });

  const { data: convData, isLoading: convsLoading } = trpc.agent.conversationsAdvanced.useQuery(
    queryInput,
    { refetchInterval: 5000, enabled: isAuthenticated }
  );

  const { data: agentsList } = trpc.agent.agents.useQuery(undefined, {
    enabled: isAuthenticated,
  });

  const selectedConversation = useMemo(
    () => convData?.conversations?.find((c: any) => c.id === selectedConversationId),
    [convData, selectedConversationId]
  );

  // Detect new customer messages and trigger notifications
  useEffect(() => {
    if (!notificationsEnabled || !convData?.conversations?.length) return;

    const currentCounts: Record<number, number> = {};
    for (const conv of convData.conversations) {
      currentCounts[conv.id] = conv.messageCount || 0;
    }

    // Only check if we have previous data (skip first load)
    if (Object.keys(prevMessageCounts).length > 0) {
      for (const conv of convData.conversations) {
        const prevCount = prevMessageCounts[conv.id] || 0;
        const currentCount = conv.messageCount || 0;
        if (currentCount > prevCount && conv.status !== "closed" && conv.status !== "resolved") {
          const newMsgCount = currentCount - prevCount;
          // In-app toast notification
          toast.info(
            `New message from ${conv.visitorName || "Visitor"}`,
            {
              description: `${newMsgCount} new message${newMsgCount > 1 ? "s" : ""} in conversation #${conv.id}`,
              action: {
                label: "View",
                onClick: () => setSelectedConversationId(conv.id),
              },
              duration: 8000,
            }
          );

          // Browser notification (only when tab is not focused)
          if (notificationPermission === "granted" && document.hidden) {
            try {
              const notification = new Notification(
                `New message from ${conv.visitorName || "Visitor"}`,
                {
                  body: `${newMsgCount} new message${newMsgCount > 1 ? "s" : ""} in conversation #${conv.id}`,
                  icon: "/favicon.ico",
                  tag: `conv-${conv.id}`,
                }
              );
              notification.onclick = () => {
                window.focus();
                setSelectedConversationId(conv.id);
                notification.close();
              };
            } catch (e) {
              // Browser notification failed silently
            }
          }
        }
      }
    }

    setPrevMessageCounts(currentCounts);
  }, [convData, notificationsEnabled, notificationPermission]); // eslint-disable-line react-hooks/exhaustive-deps

  // Bulk actions
  const bulkStatusMutation = trpc.agent.bulkUpdateStatus.useMutation({
    onSuccess: (data) => {
      toast.success(`Updated ${data.updated} conversations`);
      setSelectedIds(new Set());
      utils.agent.conversationsAdvanced.invalidate();
      utils.agent.stats.invalidate();
    },
  });

  const deleteMutation = trpc.agent.deleteConversations.useMutation({
    onSuccess: (data) => {
      toast.success(`Deleted ${data.deleted} conversations`);
      setSelectedIds(new Set());
      setSelectedConversationId(null);
      utils.agent.conversationsAdvanced.invalidate();
      utils.agent.stats.invalidate();
    },
    onError: (err) => {
      toast.error(err.message || "Failed to delete");
    },
  });

  const toggleSelectAll = useCallback(() => {
    if (!convData?.conversations) return;
    const allIds = convData.conversations.map((c: any) => c.id);
    const allSelected = allIds.every((id: number) => selectedIds.has(id));
    if (allSelected) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(allIds));
    }
  }, [convData, selectedIds]);

  const toggleSelect = useCallback((id: number, checked: boolean) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (checked) next.add(id); else next.delete(id);
      return next;
    });
  }, []);

  const clearFilters = () => {
    setStatusFilter(undefined);
    setSearchQuery("");
    setAgentFilter(undefined);
    setDateFrom("");
    setDateTo("");
    setSortBy("updated");
    setSortOrder("desc");
    setPage(1);
  };

  const hasActiveFilters = statusFilter || debouncedSearch || agentFilter || dateFrom || dateTo;

  const toggleSort = (field: typeof sortBy) => {
    if (sortBy === field) {
      setSortOrder(prev => prev === "desc" ? "asc" : "desc");
    } else {
      setSortBy(field);
      setSortOrder("desc");
    }
  };

  // If a conversation is selected, show the chat panel
  if (selectedConversationId && selectedConversation) {
    return (
      <div className="h-[calc(100vh-4rem)]">
        <div className="h-full rounded-xl border" style={{ background: "#fff", borderColor: "#e7e0d5" }}>
          <ChatPanel
            conversationId={selectedConversationId}
            conversation={selectedConversation}
            onBack={() => setSelectedConversationId(null)}
          />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold" style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}>
            Conversations
          </h1>
          <p className="text-sm mt-1" style={{ color: "#78716C", fontFamily: "'Source Sans 3', sans-serif" }}>
            Monitor and respond to customer chatbot conversations with {BOT_NAME}.
          </p>
        </div>
        <button
          onClick={toggleNotifications}
          className="flex items-center gap-2 px-3 py-2 rounded-lg border text-sm font-medium transition-all"
          style={{
            borderColor: notificationsEnabled ? "#14532D40" : "#e7e0d5",
            background: notificationsEnabled ? "#14532D08" : "transparent",
            color: notificationsEnabled ? "#14532D" : "#78716C",
            fontFamily: "'Source Sans 3', sans-serif",
          }}
          title={notificationsEnabled ? "Notifications are on — click to pause" : "Enable notifications for new customer messages"}
        >
          {notificationsEnabled ? (
            <BellRing className="w-4 h-4" />
          ) : (
            <Bell className="w-4 h-4" />
          )}
          <span className="hidden sm:inline">
            {notificationsEnabled ? "Notifications On" : "Enable Notifications"}
          </span>
        </button>
      </div>

      {/* Stats row — clickable to filter */}
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
        <StatCard
          icon={<MessageSquare className="w-4 h-4" />} label="Total Chats" value={stats?.total || 0} color="#14532D"
          isActive={!statusFilter} onClick={() => setStatusFilter(undefined)}
        />
        <StatCard
          icon={<Clock className="w-4 h-4" />} label="Active" value={stats?.active || 0} color="#0369a1"
          isActive={statusFilter === "active"} onClick={() => setStatusFilter(statusFilter === "active" ? undefined : "active")}
        />
        <StatCard
          icon={<AlertTriangle className="w-4 h-4" />} label="Escalated" value={stats?.escalated || 0} color="#C2410C"
          isActive={statusFilter === "escalated"} onClick={() => setStatusFilter(statusFilter === "escalated" ? undefined : "escalated")}
        />
        <StatCard
          icon={<CheckCircle2 className="w-4 h-4" />} label="Resolved" value={stats?.resolved || 0} color="#14532D"
          isActive={statusFilter === "resolved"} onClick={() => setStatusFilter(statusFilter === "resolved" ? undefined : "resolved")}
        />
        <StatCard
          icon={<BarChart3 className="w-4 h-4" />} label="Closed" value={stats?.closed || 0} color="#78716C"
          isActive={statusFilter === "closed"} onClick={() => setStatusFilter(statusFilter === "closed" ? undefined : "closed")}
        />
      </div>

      {/* Search & Filter toolbar */}
      <div className="rounded-xl border" style={{ background: "#fff", borderColor: "#e7e0d5" }}>
        <div className="p-3 flex items-center gap-3 flex-wrap">
          {/* Search */}
          <div className="flex-1 min-w-[200px] relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: "#a8a29e" }} />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search by name, email, customer ID, sales rep..."
              className="w-full pl-9 pr-3 py-2 rounded-lg text-sm border"
              style={{ borderColor: "#e7e0d5", fontFamily: "'Source Sans 3', sans-serif", background: "#fafaf9" }}
            />
          </div>

          {/* Toggle filters */}
          <Button
            variant="outline" size="sm"
            onClick={() => setShowFilters(!showFilters)}
            className="text-xs gap-1.5"
            style={{ borderColor: hasActiveFilters ? "#14532D40" : "#e7e0d5", color: hasActiveFilters ? "#14532D" : "#78716C" }}
          >
            <Filter className="w-3.5 h-3.5" />
            Filters
            {hasActiveFilters && (
              <span className="w-4 h-4 rounded-full text-[10px] flex items-center justify-center text-white" style={{ background: "#14532D" }}>
                {[statusFilter, agentFilter, dateFrom, dateTo].filter(Boolean).length}
              </span>
            )}
          </Button>

          {/* Sort */}
          <Select value={sortBy} onValueChange={(v) => setSortBy(v as any)}>
            <SelectTrigger className="w-[140px] text-xs h-8" style={{ borderColor: "#e7e0d5" }}>
              <ArrowUpDown className="w-3 h-3 mr-1" style={{ color: "#a8a29e" }} />
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="updated">Last Activity</SelectItem>
              <SelectItem value="created">Date Created</SelectItem>
              <SelectItem value="visitor">Visitor Name</SelectItem>
              <SelectItem value="status">Status</SelectItem>
              <SelectItem value="customerId">Customer ID</SelectItem>
              <SelectItem value="salesRep">Sales Rep</SelectItem>
              <SelectItem value="agent">Agent Name</SelectItem>
            </SelectContent>
          </Select>

          <button
            onClick={() => setSortOrder(prev => prev === "desc" ? "asc" : "desc")}
            className="w-8 h-8 rounded-lg flex items-center justify-center border hover:bg-stone-50 transition-colors"
            style={{ borderColor: "#e7e0d5" }}
            title={sortOrder === "desc" ? "Newest first" : "Oldest first"}
          >
            <ArrowUpDown className="w-3.5 h-3.5" style={{ color: "#78716C", transform: sortOrder === "asc" ? "scaleY(-1)" : undefined }} />
          </button>
        </div>

        {/* Expanded filters */}
        {showFilters && (
          <div className="px-3 pb-3 flex items-center gap-3 flex-wrap border-t pt-3" style={{ borderColor: "#f5f0e8" }}>
            {/* Agent filter */}
            <div className="flex items-center gap-2">
              <UserCheck className="w-3.5 h-3.5" style={{ color: "#a8a29e" }} />
              <Select
                value={agentFilter?.toString() || "all"}
                onValueChange={(v) => setAgentFilter(v === "all" ? undefined : Number(v))}
              >
                <SelectTrigger className="w-[160px] text-xs h-8" style={{ borderColor: "#e7e0d5" }}>
                  <SelectValue placeholder="All Agents" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Agents</SelectItem>
                  {agentsList?.map((agent: any) => (
                    <SelectItem key={agent.id} value={agent.id.toString()}>
                      {agent.name || agent.email || `Agent #${agent.id}`}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Date range */}
            <div className="flex items-center gap-2">
              <Calendar className="w-3.5 h-3.5" style={{ color: "#a8a29e" }} />
              <input
                type="date"
                value={dateFrom}
                onChange={(e) => setDateFrom(e.target.value)}
                className="px-2 py-1 rounded-lg text-xs border h-8"
                style={{ borderColor: "#e7e0d5", fontFamily: "'Source Sans 3', sans-serif" }}
                placeholder="From"
              />
              <span className="text-xs" style={{ color: "#a8a29e" }}>to</span>
              <input
                type="date"
                value={dateTo}
                onChange={(e) => setDateTo(e.target.value)}
                className="px-2 py-1 rounded-lg text-xs border h-8"
                style={{ borderColor: "#e7e0d5", fontFamily: "'Source Sans 3', sans-serif" }}
                placeholder="To"
              />
            </div>

            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="text-xs font-medium px-2 py-1 rounded-lg hover:bg-stone-100 transition-colors"
                style={{ color: "#C2410C" }}
              >
                Clear all filters
              </button>
            )}
          </div>
        )}

        {/* Bulk actions bar */}
        {selectedIds.size > 0 && (
          <div className="px-3 pb-3 flex items-center gap-3 border-t pt-3" style={{ borderColor: "#f5f0e8" }}>
            <span className="text-xs font-medium" style={{ color: "#14532D" }}>
              {selectedIds.size} selected
            </span>
            <Button
              size="sm" variant="outline" className="text-xs h-7"
              style={{ borderColor: "#14532D40", color: "#14532D" }}
              onClick={() => bulkStatusMutation.mutate({ conversationIds: Array.from(selectedIds), status: "resolved" })}
            >
              <CheckCircle2 className="w-3 h-3 mr-1" /> Resolve
            </Button>
            <Button
              size="sm" variant="outline" className="text-xs h-7"
              style={{ borderColor: "#78716C40", color: "#78716C" }}
              onClick={() => bulkStatusMutation.mutate({ conversationIds: Array.from(selectedIds), status: "closed" })}
            >
              <X className="w-3 h-3 mr-1" /> Close
            </Button>
            {user?.role === "admin" && (
              <Button
                size="sm" variant="outline" className="text-xs h-7"
                style={{ borderColor: "#dc262640", color: "#dc2626" }}
                onClick={() => {
                  if (confirm(`Delete ${selectedIds.size} conversation(s)? This cannot be undone.`)) {
                    deleteMutation.mutate({ conversationIds: Array.from(selectedIds) });
                  }
                }}
              >
                <Trash2 className="w-3 h-3 mr-1" /> Delete
              </Button>
            )}
            <button
              onClick={() => setSelectedIds(new Set())}
              className="text-xs ml-auto" style={{ color: "#a8a29e" }}
            >
              Deselect all
            </button>
          </div>
        )}

        {/* Table header */}
        <div className="flex items-center gap-3 px-3 py-2 border-t text-[11px] font-semibold uppercase tracking-wider" style={{ borderColor: "#f5f0e8", color: "#a8a29e", fontFamily: "'Source Sans 3', sans-serif" }}>
          <input
            type="checkbox"
            checked={convData?.conversations?.length ? convData.conversations.every((c: any) => selectedIds.has(c.id)) : false}
            onChange={toggleSelectAll}
            className="w-4 h-4 rounded border-stone-300 accent-green-800 shrink-0"
          />
          <button onClick={() => toggleSort("visitor")} className="w-36 shrink-0 text-left flex items-center gap-1 hover:text-stone-600">
            Visitor {sortBy === "visitor" && <ArrowUpDown className="w-3 h-3" />}
          </button>
          <button onClick={() => toggleSort("customerId")} className="w-28 shrink-0 text-left flex items-center gap-1 hover:text-stone-600 hidden lg:flex">
            Customer ID {sortBy === "customerId" && <ArrowUpDown className="w-3 h-3" />}
          </button>
          <button onClick={() => toggleSort("salesRep")} className="w-28 shrink-0 text-left flex items-center gap-1 hover:text-stone-600 hidden lg:flex">
            Sales Rep {sortBy === "salesRep" && <ArrowUpDown className="w-3 h-3" />}
          </button>
          <button onClick={() => toggleSort("agent")} className="w-28 shrink-0 text-left flex items-center gap-1 hover:text-stone-600 hidden lg:flex">
            Agent {sortBy === "agent" && <ArrowUpDown className="w-3 h-3" />}
          </button>
          <button onClick={() => toggleSort("status")} className="w-24 shrink-0 text-left flex items-center gap-1 hover:text-stone-600">
            Status {sortBy === "status" && <ArrowUpDown className="w-3 h-3" />}
          </button>
          <span className="w-14 shrink-0">Msgs</span>
          <span className="flex-1 hidden xl:block">Contact</span>
          <button onClick={() => toggleSort("updated")} className="w-28 shrink-0 text-right flex items-center gap-1 justify-end hover:text-stone-600 hidden md:flex">
            Last Active {sortBy === "updated" && <ArrowUpDown className="w-3 h-3" />}
          </button>
        </div>

        {/* Conversation rows */}
        <div className="min-h-[200px]">
          {convsLoading ? (
            <div className="text-center py-12 text-sm" style={{ color: "#a8a29e" }}>
              <MessageSquare className="w-6 h-6 mx-auto mb-2 animate-pulse" style={{ color: "#d6d3d1" }} />
              Loading conversations...
            </div>
          ) : !convData?.conversations?.length ? (
            <div className="text-center py-12">
              <MessageSquare className="w-10 h-10 mx-auto mb-3" style={{ color: "#d6d3d1" }} />
              <p className="text-sm font-medium" style={{ color: "#78716C" }}>
                {hasActiveFilters ? "No conversations match your filters" : "No conversations yet"}
              </p>
              <p className="text-xs mt-1" style={{ color: "#a8a29e" }}>
                {hasActiveFilters
                  ? "Try adjusting your search or filter criteria"
                  : `Conversations will appear here when visitors chat with ${BOT_NAME}`}
              </p>
              {hasActiveFilters && (
                <button
                  onClick={clearFilters}
                  className="mt-3 text-xs font-medium px-3 py-1.5 rounded-lg"
                  style={{ background: "#14532D12", color: "#14532D" }}
                >
                  Clear all filters
                </button>
              )}
            </div>
          ) : (
            convData.conversations.map((conv: any) => (
              <ConversationRow
                key={conv.id}
                conversation={conv}
                isSelected={conv.id === selectedConversationId}
                isChecked={selectedIds.has(conv.id)}
                onClick={() => setSelectedConversationId(conv.id)}
                onCheck={(checked) => toggleSelect(conv.id, checked)}
              />
            ))
          )}
        </div>

        {/* Pagination */}
        {convData && convData.totalPages > 1 && (
          <PaginationBar
            page={convData.page}
            totalPages={convData.totalPages}
            total={convData.total}
            pageSize={convData.pageSize}
            onPageChange={setPage}
          />
        )}
      </div>
    </div>
  );
}
