"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import {
  Wallet,
  LayoutDashboard,
  FileText,
  Send,
  Users,
  FolderOpen,
  PanelLeft,
  CheckSquare,
  ClipboardList,
  BookOpen,
  Library,
  Settings,
  Activity,
  BarChart3,
  Newspaper,
  Inbox,
  SlidersHorizontal,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { useAuthStore } from "@/lib/store/auth-store";
import { adminApi } from "@/lib/api/client";
import { usePaymentsEnabled } from "@/lib/hooks/use-payments-enabled";
import { useTranslation } from "@/lib/hooks/use-translation";
import type { UserRole } from "@/types";

interface NavItem {
  labelKey: string;        // CMS fieldKey like "dashboard", "submit_paper"
  labelFallback: string;   // English fallback
  href: string;
  icon: React.ElementType;
}

const roleNavItems: Record<UserRole, NavItem[]> = {
  AUTHOR: [
    { labelKey: "author_dashboard", labelFallback: "Dashboard", href: "/author", icon: LayoutDashboard },
    { labelKey: "submit_paper", labelFallback: "Submit Paper", href: "/submit", icon: Send },
    { labelKey: "my_papers", labelFallback: "My Papers", href: "/author", icon: FileText },
  ],
  REVIEWER: [
    { labelKey: "reviewer_dashboard", labelFallback: "Dashboard", href: "/reviewer", icon: LayoutDashboard },
    { labelKey: "pending_reviews", labelFallback: "Pending Reviews", href: "/reviewer?tab=pending", icon: ClipboardList },
    { labelKey: "completed_reviews", labelFallback: "Completed Reviews", href: "/reviewer?tab=completed", icon: CheckSquare },
  ],
  ADMIN: [
    { labelKey: "admin_dashboard", labelFallback: "Dashboard", href: "/admin/dashboard", icon: LayoutDashboard },
    { labelKey: "admin_papers", labelFallback: "Papers", href: "/admin/papers", icon: FileText },
    { labelKey: "admin_users", labelFallback: "Users", href: "/admin/users", icon: Users },
    { labelKey: "admin_payments", labelFallback: "Payments", href: "/admin/payments", icon: Wallet },
    { labelKey: "admin_categories", labelFallback: "Categories", href: "/admin/categories", icon: FolderOpen },
    { labelKey: "admin_page_content", labelFallback: "Page Content", href: "/admin/page-content", icon: PanelLeft },
    { labelKey: "admin_news", labelFallback: "News", href: "/admin/news", icon: Newspaper },
    { labelKey: "admin_inquiries", labelFallback: "Inquiries", href: "/admin/inquiries", icon: Inbox },
    { labelKey: "admin_magazine", labelFallback: "Magazine Builder", href: "/magazine", icon: Library },
    { labelKey: "admin_activity", labelFallback: "Activity Log", href: "/admin/activity", icon: Activity },
    { labelKey: "admin_api_usage", labelFallback: "API Usage", href: "/admin/api-usage", icon: BarChart3 },
    // "Journal Settings", not "Settings": every role already has a personal
    // /settings link in the footer below, and two identically named items in one
    // sidebar is a coin toss for the reader.
    { labelKey: "admin_settings", labelFallback: "Journal Settings", href: "/admin/settings", icon: SlidersHorizontal },
  ],
};

export function DashboardSidebar() {
  const pathname = usePathname();
  const { user } = useAuthStore();
  const { t: cms } = useTranslation("SIDEBAR");

  /**
   * Payments waiting on a decision, shown as a badge beside the Payments link.
   *
   * Email tells the editor once; this tells them every time they look at any
   * admin screen, and it works whether or not SMTP is configured. The failure
   * mode of a manual queue is not a wrong decision, it is no decision.
   */
  const awaiting = useQuery({
    queryKey: ["admin", "payments", "summary"],
    queryFn: async () => (await adminApi.paymentSummary()).data as { awaitingCount: number },
    enabled: user?.role === "ADMIN",
    refetchInterval: 60_000,
    refetchOnWindowFocus: true,
  });
  const awaitingCount = awaiting.data?.awaitingCount ?? 0;

  const { paymentsEnabled } = usePaymentsEnabled();

  if (!user) return <aside className="hidden w-64 shrink-0 border-r border-gray-200 bg-white p-4 md:block" />;

  // Payments stays reachable while claims are still outstanding, even with the
  // section switched off — those authors' money may genuinely have moved, and
  // hiding the only screen that can settle them would strand the claims.
  const items = (roleNavItems[user.role] ?? []).filter(
    (item) => item.href !== "/admin/payments" || paymentsEnabled || awaitingCount > 0,
  );

  return (
    <aside className="hidden w-64 shrink-0 border-r border-gray-200 bg-white p-4 md:block">
      {/* Role heading */}
      <div className="mb-4 flex items-center gap-2 px-3">
        <BookOpen className="h-5 w-5 text-indigo-600" />
        <span className="text-sm font-semibold text-gray-500 uppercase tracking-wider">
          {user.role}
        </span>
      </div>

      <nav className="flex flex-col gap-1">
        {items.map((item) => {
          const Icon = item.icon;
          const isActive =
            pathname === item.href ||
            (item.href !== "/" && pathname.startsWith(item.href.split("?")[0]));

          return (
            <Link
              key={item.href + item.labelKey}
              href={item.href}
              className={cn(
                "flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
                isActive
                  ? "bg-indigo-50 text-indigo-700"
                  : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
              )}
            >
              <Icon
                className={cn(
                  "h-4.5 w-4.5",
                  isActive ? "text-indigo-600" : "text-gray-400"
                )}
              />
              <span className="flex-1">{cms("nav." + item.labelKey, item.labelFallback)}</span>
              {item.href === "/admin/payments" && awaitingCount > 0 && (
                <span
                  title="भुगतान सत्यापन हेतु प्रतीक्षारत / Payments awaiting your confirmation"
                  className="rounded-full bg-red-600 px-1.5 py-0.5 text-[10px] font-bold text-white"
                >
                  {awaitingCount > 99 ? "99+" : awaitingCount}
                </span>
              )}
            </Link>
          );
        })}

        {/* Settings — common to all roles */}
        <div className="mt-4 border-t border-gray-100 pt-3">
          <Link
            href="/settings"
            className={cn(
              "flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
              pathname === "/settings"
                ? "bg-indigo-50 text-indigo-700"
                : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
            )}
          >
            <Settings
              className={cn(
                "h-4.5 w-4.5",
                pathname === "/settings" ? "text-indigo-600" : "text-gray-400"
              )}
            />
            {cms("nav.settings", "Settings")}
          </Link>
        </div>
      </nav>
    </aside>
  );
}
