'use client';

import { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import { useNotifications } from '@/contexts/NotificationContext';
import { useMessages } from '@/contexts/MessagesContext';
import { UnreadBadge } from '@/components/ui/unread-badge';
import {
  LayoutDashboard,
  Bookmark,
  Briefcase,
  MessageCircle,
  Bell,
  Star,
  User,
  UserCircle,
  Settings,
  Users,
  FolderOpen,
  BarChart3,
  ShieldCheck,
  ClipboardList,
  Handshake,
  CalendarClock,
  Trash2,
  Menu,
  X,
  LogOut,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { JOBS_FEATURE_ENABLED } from '@/lib/features';
import { BrandLogo } from '@/components/brand/BrandLogo';

export type DashboardRole = 'customer' | 'worker' | 'admin';

interface NavItem {
  href: string;
  label: string;
  icon: LucideIcon;
  group?: string;
}

const customerNavAll: NavItem[] = [
  { href: '/customer/dashboard', label: 'Dashboard', icon: LayoutDashboard, group: 'Overview' },
  { href: '/customer/jobs', label: 'My Jobs', icon: Briefcase, group: 'Jobs' },
  { href: '/workers', label: 'Browse Workers', icon: Users, group: 'Directory' },
  { href: '/customer/jobs/create', label: 'Create Job', icon: ClipboardList, group: 'Jobs' },
  { href: '/customer/saved-workers', label: 'Saved Workers', icon: Bookmark, group: 'Directory' },
  { href: '/customer/hire-invitations', label: 'Hire invitations', icon: Handshake, group: 'Directory' },
  { href: '/customer/messages', label: 'Messages', icon: MessageCircle, group: 'Communication' },
  { href: '/customer/notifications', label: 'Notifications', icon: Bell, group: 'Communication' },
  { href: '/customer/reviews', label: 'Reviews', icon: Star, group: 'Account' },
  { href: '/customer/verification', label: 'Verification', icon: ShieldCheck, group: 'Account' },
  { href: '/customer/profile', label: 'Profile', icon: User, group: 'Account' },
];

const workerNavAll: NavItem[] = [
  { href: '/worker/dashboard', label: 'Dashboard', icon: LayoutDashboard, group: 'Overview' },
  { href: '/worker/jobs', label: 'Available Jobs', icon: Briefcase, group: 'Jobs' },
  { href: '/worker/applications', label: 'My Applications', icon: ClipboardList, group: 'Jobs' },
  { href: '/worker/accepted', label: 'Accepted Jobs', icon: Briefcase, group: 'Jobs' },
  { href: '/worker/hire-invitations', label: 'Hire invitations', icon: Handshake, group: 'Directory' },
  { href: '/worker/messages', label: 'Messages', icon: MessageCircle, group: 'Communication' },
  { href: '/worker/notifications', label: 'Notifications', icon: Bell, group: 'Communication' },
  { href: '/worker/profile', label: 'Profile', icon: User, group: 'Account' },
  { href: '/worker/portfolio', label: 'Portfolio', icon: FolderOpen, group: 'Account' },
  { href: '/worker/verification', label: 'Verification', icon: ShieldCheck, group: 'Account' },
  { href: '/worker/ratings', label: 'Ratings', icon: Star, group: 'Account' },
  { href: '/worker/availability', label: 'Availability', icon: CalendarClock, group: 'Account' },
];

const adminNavAll: NavItem[] = [
  { href: '/admin', label: 'Dashboard', icon: LayoutDashboard, group: 'Overview' },
  { href: '/admin/users', label: 'All users', icon: Users, group: 'People' },
  { href: '/admin/workers', label: 'Workers', icon: Briefcase, group: 'People' },
  { href: '/admin/customers', label: 'Customers', icon: UserCircle, group: 'People' },
  { href: '/admin/deletions', label: 'Account removals', icon: Trash2, group: 'People' },
  { href: '/admin/verifications', label: 'Verifications', icon: ShieldCheck, group: 'Identity' },
  { href: '/admin/jobs', label: 'Jobs', icon: ClipboardList, group: 'Catalog' },
  { href: '/admin/categories', label: 'Categories', icon: FolderOpen, group: 'Catalog' },
  { href: '/admin/reports', label: 'Reports', icon: BarChart3, group: 'System' },
  { href: '/admin/settings', label: 'Settings', icon: Settings, group: 'System' },
];

const JOBS_NAV_HREFS = new Set([
  '/customer/jobs',
  '/customer/jobs/create',
  '/worker/jobs',
  '/worker/applications',
  '/worker/accepted',
  '/admin/jobs',
]);

function filterNavForFeatures(items: NavItem[]): NavItem[] {
  if (JOBS_FEATURE_ENABLED) return items;
  return items.filter((item) => !JOBS_NAV_HREFS.has(item.href));
}

export const dashboardNavItems: Record<DashboardRole, NavItem[]> = {
  customer: filterNavForFeatures(customerNavAll),
  worker: filterNavForFeatures(workerNavAll),
  admin: filterNavForFeatures(adminNavAll),
};

function DashboardNavList({
  role,
  onNavigate,
  className,
}: {
  role: DashboardRole;
  onNavigate?: () => void;
  className?: string;
}) {
  const pathname = usePathname();
  const { unreadCount: notificationUnreadCount } = useNotifications();
  const { unreadCount: messageUnreadCount } = useMessages();
  const items = dashboardNavItems[role];

  return (
    <nav className={cn('space-y-0.5', className)}>
      {items.map((item, index) => {
        const isActive = pathname === item.href || pathname.startsWith(item.href + '/');
        const showGroup = item.group && (index === 0 || items[index - 1]?.group !== item.group);

        return (
          <div key={item.href}>
            {showGroup ? (
              <p className="mb-1.5 mt-4 px-3 text-[10px] font-semibold uppercase tracking-wider text-slate-500 first:mt-0">
                {item.group}
              </p>
            ) : null}
            <Link
              href={item.href}
              onClick={onNavigate}
              className={cn(
                'flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-colors',
                isActive
                  ? 'bg-primary text-white'
                  : 'text-slate-400 hover:bg-slate-800 hover:text-white'
              )}
            >
              <item.icon className="h-4 w-4 shrink-0" />
              <span className="flex-1">{item.label}</span>
              {item.label === 'Messages' && <UnreadBadge count={messageUnreadCount} />}
              {item.label === 'Notifications' && <UnreadBadge count={notificationUnreadCount} />}
            </Link>
          </div>
        );
      })}
    </nav>
  );
}

function DashboardSidebarFooter({ onNavigate }: { onNavigate?: () => void }) {
  const { user, logout } = useAuth();

  return (
    <div className="shrink-0 border-t border-slate-800 p-3">
      {user ? (
        <p className="mb-2 truncate px-3 text-xs text-slate-500">
          {user.firstName} {user.lastName}
        </p>
      ) : null}
      <button
        type="button"
        onClick={() => {
          onNavigate?.();
          void logout();
        }}
        className="flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium text-slate-400 transition-colors hover:bg-slate-800 hover:text-red-400"
      >
        <LogOut className="h-4 w-4 shrink-0" />
        Sign out
      </button>
    </div>
  );
}

export function DashboardSidebar({ role }: { role: DashboardRole }) {
  return (
    <aside className="hidden lg:flex w-64 shrink-0 flex-col border-r border-slate-800 bg-slate-900 sticky top-0 h-screen text-slate-300">
      <div className="p-5 border-b border-slate-800">
        <BrandLogo
          variant="header"
          href="/"
          tagline={`${role} portal`}
        />
      </div>
      <div className="flex-1 overflow-y-auto p-3">
        <DashboardNavList role={role} />
      </div>
      {(role === 'worker' || role === 'customer') && <DashboardSidebarFooter />}
    </aside>
  );
}

function DashboardMobileMenu({
  role,
  open,
  onClose,
}: {
  role: DashboardRole;
  open: boolean;
  onClose: () => void;
}) {
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 lg:hidden">
      <button
        type="button"
        className="absolute inset-0 bg-black/50"
        aria-label="Close menu"
        onClick={onClose}
      />
      <aside className="absolute inset-y-0 left-0 flex w-[min(100vw-3rem,18rem)] flex-col border-r border-slate-800 bg-slate-900 text-slate-300 shadow-xl">
        <div className="flex items-center justify-between border-b border-slate-800 p-4">
          <BrandLogo
            variant="header"
            href="/"
            onClick={onClose}
            tagline={`${role} portal`}
          />
          <button
            type="button"
            onClick={onClose}
            className="rounded-md p-2 text-slate-400 hover:bg-slate-800 hover:text-white"
            aria-label="Close menu"
          >
            <X className="h-5 w-5" />
          </button>
        </div>
        <div className="flex-1 overflow-y-auto p-3">
          <DashboardNavList role={role} onNavigate={onClose} />
        </div>
        {(role === 'worker' || role === 'customer') && (
          <DashboardSidebarFooter onNavigate={onClose} />
        )}
      </aside>
    </div>
  );
}

function DashboardMobileHeader({
  role,
  title,
  onOpenMenu,
}: {
  role: DashboardRole;
  title?: string;
  onOpenMenu: () => void;
}) {
  const notificationsHref =
    role === 'worker'
      ? '/worker/notifications'
      : role === 'customer'
        ? '/customer/notifications'
        : null;

  return (
    <div className="sticky top-0 z-30 flex items-center gap-3 border-b border-border bg-surface px-4 py-3 lg:hidden">
      <button
        type="button"
        onClick={onOpenMenu}
        className="flex h-10 w-10 items-center justify-center rounded-lg text-slate-700 hover:bg-slate-100"
        aria-label="Open menu"
      >
        <Menu className="h-5 w-5" />
      </button>
      <h1 className="flex-1 truncate text-base font-bold text-slate-900">
        {title || 'eHandyHire'}
      </h1>
      {notificationsHref ? (
        <Link
          href={notificationsHref}
          className="flex h-10 w-10 items-center justify-center rounded-lg text-slate-700 hover:bg-slate-100"
          aria-label="Notifications"
        >
          <Bell className="h-5 w-5" />
        </Link>
      ) : null}
    </div>
  );
}

export function DashboardLayout({
  role,
  children,
  title,
  chatMode,
  hideMobileHeader,
  flush,
}: {
  role: DashboardRole;
  children: React.ReactNode;
  title?: string;
  /** Full-viewport chat: sidebar + fixed chat panel, no page scroll */
  chatMode?: boolean;
  /** Hide the mobile top bar (e.g. thread view with its own header) */
  hideMobileHeader?: boolean;
  /** Remove main content padding (full-bleed layouts) */
  flush?: boolean;
}) {
  const [menuOpen, setMenuOpen] = useState(false);

  if (chatMode) {
    return (
      <div className="flex h-dvh overflow-hidden bg-background">
        <DashboardSidebar role={role} />
        <DashboardMobileMenu role={role} open={menuOpen} onClose={() => setMenuOpen(false)} />
        <div className="flex min-w-0 flex-1 flex-col lg:flex-row">
          <DashboardMobileHeader
            role={role}
            title={title || 'Messages'}
            onOpenMenu={() => setMenuOpen(true)}
          />
          <div className="flex min-h-0 flex-1 flex-col">{children}</div>
        </div>
      </div>
    );
  }

  return (
    <div
      className={cn(
        'flex bg-background',
        flush ? 'h-dvh overflow-hidden' : 'min-h-screen'
      )}
    >
      <DashboardSidebar role={role} />
      <DashboardMobileMenu role={role} open={menuOpen} onClose={() => setMenuOpen(false)} />
      <main
        className={cn(
          'flex min-h-0 flex-1 flex-col',
          flush ? 'overflow-hidden pb-0' : hideMobileHeader ? 'pb-0' : 'pb-20 lg:pb-6'
        )}
      >
        {!hideMobileHeader && (
          <DashboardMobileHeader
            role={role}
            title={title}
            onOpenMenu={() => setMenuOpen(true)}
          />
        )}
        {title ? (
          <div className="hidden shrink-0 border-b border-border bg-surface px-4 py-4 lg:block lg:px-8">
            <h1 className="text-xl font-bold text-slate-900">{title}</h1>
          </div>
        ) : null}
        <div
          className={cn(
            flush ? 'flex min-h-0 flex-1 flex-col p-0' : 'p-4 lg:p-8'
          )}
        >
          {children}
        </div>
      </main>
    </div>
  );
}
