"use client";

import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { signOut } from "next-auth/react";
import {
  BarChart3, Calendar, PenSquare, Inbox, Headphones, Settings, LogOut, Menu, ChevronRight, ClipboardCheck, LayoutGrid, Plus, FileText, LineChart, Megaphone,
} from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { Skeleton } from "@/components/ui/skeleton";
import { SessionProvider } from "@/components/providers/session-provider";
import { NotificationBell } from "@/components/notifications/NotificationBell";
import type { UserRole } from "@/lib/types";

const CONTENT_NAV = [
  { href: "/dashboard", label: "Overview", icon: BarChart3 },
  { href: "/dashboard/calendar", label: "Calendar", icon: Calendar },
  { href: "/dashboard/compose", label: "Compose", icon: PenSquare },
  { href: "/dashboard/drafts", label: "Drafts", icon: FileText },
  { href: "/dashboard/campaigns", label: "Campaigns", icon: Megaphone },
];

const INSIGHTS_NAV = [
  { href: "/dashboard/analytics", label: "Analytics", icon: LineChart },
  { href: "/dashboard/inbox", label: "Inbox", icon: Inbox },
  { href: "/dashboard/listening", label: "Listening", icon: Headphones },
];

const ROLE_BADGE: Record<UserRole, string> = {
  ADMIN: "bg-pink-100 text-pink-600",
  EDITOR: "bg-blue-50 text-blue-600",
  VIEWER: "bg-gray-100 text-gray-600",
};

function SectionLabel({ children }: { children: React.ReactNode }) {
  return (
    <p className="px-5 pt-4 pb-1 text-xs font-medium uppercase tracking-wider text-gray-400">
      {children}
    </p>
  );
}

function SidebarNav() {
  const { data: session, status } = useSession();
  const pathname = usePathname();
  const role = (session?.user as { role?: UserRole })?.role;
  const [inboxUnread, setInboxUnread] = useState(0);
  const [pendingApprovals, setPendingApprovals] = useState(0);

  const fetchBadgeCounts = () => {
    if (status !== "authenticated") return;
    fetch("/api/v1/inbox?status=UNREAD")
      .then((res) => (res.ok ? res.json() : []))
      .then((data: unknown[]) => setInboxUnread(data.length))
      .catch(() => {});
    if (role === "ADMIN") {
      fetch("/api/v1/posts/pending")
        .then((res) => (res.ok ? res.json() : []))
        .then((data: unknown[]) => setPendingApprovals(data.length))
        .catch(() => {});
    }
  };

  useEffect(() => {
    fetchBadgeCounts();
  }, [status, pathname, role]);

  useEffect(() => {
    const handler = () => fetchBadgeCounts();
    window.addEventListener("approvals-changed", handler);
    return () => window.removeEventListener("approvals-changed", handler);
  }, [status, role]);

  if (status === "loading") {
    return (
      <div className="flex h-full flex-col p-4 space-y-4">
        <Skeleton className="h-6 w-32 bg-gray-100" />
        {Array.from({ length: 5 }).map((_, i) => (
          <Skeleton key={i} className="h-8 w-full bg-gray-100" />
        ))}
      </div>
    );
  }

  const settingsItem = role === "ADMIN"
    ? [{ href: "/dashboard/settings", label: "Settings", icon: Settings }]
    : [];

  const renderNavItem = ({ href, label, icon: Icon }: { href: string; label: string; icon: typeof BarChart3 }) => {
    const isActive = pathname === href || (href !== "/dashboard" && pathname.startsWith(href));
    const showBadge = (href === "/dashboard/inbox" && inboxUnread > 0) || (href === "/dashboard/approvals" && pendingApprovals > 0);
    const badgeCount = href === "/dashboard/inbox" ? inboxUnread : pendingApprovals;
    const isCompose = href === "/dashboard/compose";
    if (isCompose) {
      return (
        <div key={href} className="px-2 py-0.5">
          <Link
            href={href}
            className={`flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm font-semibold transition-colors shadow-sm ${
              isActive
                ? "bg-blue-700 text-white shadow-blue-200"
                : "bg-blue-600 text-white hover:bg-blue-700 shadow-blue-100"
            }`}
          >
            <Plus className="h-4 w-4" />
            Compose
          </Link>
        </div>
      );
    }
    return (
      <div key={href} className="px-2 py-0.5">
        <Link
          href={href}
          className={`flex items-center gap-2.5 px-3 py-1.5 rounded-lg text-sm transition-colors ${
            isActive
              ? "bg-gray-100 text-gray-900 font-medium"
              : "text-gray-600 hover:bg-gray-50"
          }`}
        >
          <Icon className="h-[18px] w-[18px]" />
          {label}
          {showBadge && (
            <span className="ml-auto rounded-full bg-blue-500 px-1.5 py-0.5 text-[10px] font-medium text-white leading-none">
              {badgeCount}
            </span>
          )}
        </Link>
      </div>
    );
  };

  return (
    <div className="flex h-full flex-col bg-white">
      {/* Logo area */}
      <Link href="/dashboard" className="flex items-center gap-2 px-4 py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors">
        <div className="h-8 w-8 bg-gray-900 rounded flex items-center justify-center">
          <span className="text-white text-xs font-bold">P</span>
        </div>
        <span className="text-sm font-medium text-gray-800">PingCAP Social</span>
      </Link>

      {/* Navigation */}
      <nav className="flex-1 space-y-0.5 overflow-y-auto pt-2">
        <SectionLabel>Content</SectionLabel>
        {CONTENT_NAV.map(renderNavItem)}

        <SectionLabel>Insights</SectionLabel>
        {INSIGHTS_NAV.map(renderNavItem)}

        {role === "ADMIN" && (
          <>
            <SectionLabel>Review</SectionLabel>
            {[
              { href: "/dashboard/approvals", label: "Approvals", icon: ClipboardCheck },
              { href: "/dashboard/queue", label: "Queue", icon: LayoutGrid },
            ].map(renderNavItem)}
          </>
        )}

        {settingsItem.length > 0 && (
          <>
            <SectionLabel>Settings</SectionLabel>
            {settingsItem.map(renderNavItem)}
          </>
        )}
      </nav>

      {/* User area */}
      <div className="border-t border-gray-100 p-3">
        <div className="flex items-center gap-3">
          <Avatar className="h-8 w-8">
            <AvatarImage src={session?.user?.image || undefined} />
            <AvatarFallback className="bg-gray-100 text-xs text-gray-700">
              {session?.user?.name?.slice(0, 2).toUpperCase() || "?"}
            </AvatarFallback>
          </Avatar>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-gray-900 truncate">{session?.user?.name}</p>
            {role && (
              <Badge className={`text-[10px] px-1.5 py-0 rounded-full ${ROLE_BADGE[role]}`}>
                {role}
              </Badge>
            )}
          </div>
          <NotificationBell />
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-gray-400 hover:text-gray-600 hover:bg-gray-50"
            onClick={() => signOut({ callbackUrl: "/login" })}
          >
            <LogOut className="h-4 w-4" />
          </Button>
        </div>
      </div>
    </div>
  );
}

function DashboardShell({ children }: { children: React.ReactNode }) {
  return (
    <div className="flex h-screen overflow-x-hidden">
      {/* Main content area first in DOM so mobile bell is first for a11y/test selectors */}
      <div className="flex flex-1 flex-col min-w-0 md:order-2">
        <header className="flex h-14 items-center gap-4 border-b border-gray-100 bg-white px-4 md:hidden">
          <Sheet>
            <SheetTrigger
              render={<Button variant="ghost" size="icon"><Menu className="h-5 w-5" /></Button>}
            />
            <SheetContent side="left" className="w-52 p-0 bg-white border-r border-gray-200">
              <SidebarNav />
            </SheetContent>
          </Sheet>
          <Link href="/dashboard" className="flex items-center gap-2 flex-1">
            <div className="h-6 w-6 bg-gray-900 rounded flex items-center justify-center">
              <span className="text-white text-[10px] font-bold">P</span>
            </div>
            <span className="text-sm font-medium text-gray-800">PingCAP Social</span>
          </Link>
          <NotificationBell />
        </header>

        <main className="flex-1 overflow-y-auto overflow-x-hidden bg-white p-4 md:p-6">
          {children}
        </main>
      </div>

      {/* Desktop sidebar — second in DOM but visually first on desktop via order */}
      <aside className="hidden w-52 shrink-0 border-r border-gray-200 md:block md:order-1">
        <SidebarNav />
      </aside>
    </div>
  );
}

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  return (
    <SessionProvider>
      <DashboardShell>{children}</DashboardShell>
    </SessionProvider>
  );
}
