'use client';

import Link from 'next/link';
import { Badge } from '@/components/ui/badge';
import { Building } from 'lucide-react';
import { CompactLanguageSwitcher } from './compact-language-switcher';
import { DashboardUserMenu } from './dashboard-user-menu';
import { getIconComponent } from './icon-map';
import { useEffect, useState, type MouseEvent } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { cn } from '@/lib/utils';

interface NavLink {
  href: string;
  label: string;
  iconName: string;
  badge?: number | null;
  children?: NavLink[];
}

export function SidebarNav({ 
  navLinks, 
  appName, 
  appLogoUrl,
  isPos,
  isAdmin,
  employeeCashAccountCode,
  currentLocale,
  languageT,
  userName,
  userInitial,
  userAvatarUrl,
  userAvatarHint,
  settingsLabel,
  supportLabel,
  logoutLabel,
}: { 
  navLinks: NavLink[]; 
  appName: string;
  appLogoUrl?: string;
  isPos: boolean;
  isAdmin: boolean;
  employeeCashAccountCode?: string;
  currentLocale: string;
  languageT: any;
  userName: string;
  userInitial: string;
  userAvatarUrl?: string;
  userAvatarHint?: string;
  settingsLabel: string;
  supportLabel: string;
  logoutLabel: string;
}) {
  const [collapsed, setCollapsed] = useState(true);
  const [liveWorkTasksBadge, setLiveWorkTasksBadge] = useState<number | null>(null);
  const [liveMyTasksBadge, setLiveMyTasksBadge] = useState<number | null>(null);
  const pathname = usePathname();
  const router = useRouter();
  const isPosPage = pathname?.startsWith('/admin/sales/pos');

  useEffect(() => {
    let isMounted = true;

    const updateNotifications = async () => {
      try {
        const response = await fetch('/api/employee/work-tasks/notifications', {
          method: 'GET',
          cache: 'no-store',
        });
        if (!response.ok) return;

        const payload = await response.json() as { workTasksCount?: number; myTasksCount?: number };
        if (!isMounted) return;

        const workTasksCount = Number(payload?.workTasksCount || 0);
        const myTasksCount = Number(payload?.myTasksCount || 0);
        setLiveWorkTasksBadge(workTasksCount > 0 ? workTasksCount : null);
        setLiveMyTasksBadge(myTasksCount > 0 ? myTasksCount : null);
      } catch {
        // Keep previous badge value when polling fails.
      }
    };

    void updateNotifications();
    const intervalId = window.setInterval(() => {
      void updateNotifications();
    }, 15000);

    return () => {
      isMounted = false;
      window.clearInterval(intervalId);
    };
  }, []);

  const handlePosLinkClick = async (event: MouseEvent<HTMLAnchorElement>, href: string) => {
    if (href !== '/admin/sales/pos') return;
    event.preventDefault();
    const hasEmployeeCashAccount = String(employeeCashAccountCode || '').trim().length > 0;
    if (!hasEmployeeCashAccount) {
      window.alert('لا يمكنك الشروع في البيع من خلال نقطة البيع لعدم وجود صندوق موظف مفعّل.');
      return;
    }
    if (typeof document !== 'undefined' && !document.fullscreenElement) {
      void document.documentElement.requestFullscreen().catch(() => {
        // Browser may block fullscreen in some cases; continue navigation regardless.
      });
    }
    router.push(href);
  };

  // Accordion: track which parent sections are expanded
  const [expandedSections, setExpandedSections] = useState<Set<string>>(() => {
    // Auto-expand the section whose child matches current path
    const expanded = new Set<string>();
    return expanded;
  });

  const toggleSection = (href: string) => {
    setExpandedSections((prev) => {
      const next = new Set(prev);
      if (next.has(href)) {
        next.delete(href);
      } else {
        next.add(href);
      }
      return next;
    });
  };
  const toggleLabel = collapsed ? 'إظهار القائمة' : 'إخفاء القائمة';

  const resolveLiveBadge = (href: string, fallback?: number | null) => {
    if (href === '/employee/work-tasks') return liveWorkTasksBadge ?? fallback ?? null;
    if (href === '/employee/my-tasks') return liveMyTasksBadge ?? fallback ?? null;
    return fallback ?? null;
  };

  if (isPosPage) {
    return null;
  }

  const asideWidth = collapsed ? 'sm:w-12' : 'sm:w-64';
  const brandTextClass = collapsed ? 'hidden' : 'truncate';
  const navTextClass = collapsed ? 'hidden' : 'block';
  const badgeClass = collapsed ? 'hidden' : 'flex';

  return (
    <aside
      className={cn('hidden h-screen flex-col border-e bg-card sm:sticky sm:top-0 sm:flex transition-[width] duration-200 overflow-hidden', asideWidth)}
      onDoubleClick={() => setCollapsed((v) => !v)}
    >
      <div className="flex h-full flex-col">
        <div className={cn('relative flex h-14 items-center border-e', collapsed ? 'px-1.5 justify-center' : 'px-6')}>
          {(() => {
            const homeHref = isPos ? '/admin/sales/pos' : isAdmin ? '/admin' : '/employee';
            return (
          <Link
            href={homeHref}
            onClick={(event) => void handlePosLinkClick(event, homeHref)}
            className="flex items-center gap-2 font-semibold text-lg"
          >
            {appLogoUrl ? (
              <img src={appLogoUrl} alt={appName} className="h-8 w-auto max-w-full" />
            ) : (
              <Building className="h-6 w-6 text-primary" />
            )}
            <span className={brandTextClass}>{appName}</span>
          </Link>
            );
          })()}
          <button
            type="button"
            aria-label={toggleLabel}
            title={toggleLabel}
            onClick={() => setCollapsed((v) => !v)}
            className="absolute end-1.5 top-1/2 -translate-y-1/2 rounded-md border px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-muted"
          >
            {collapsed ? '›' : '‹'}
          </button>
        </div>
        <div className="flex-1 overflow-auto py-2">
          <nav className={cn('grid items-start text-sm font-medium', collapsed ? 'px-1' : 'px-4')} aria-label="Sidebar navigation">
            {navLinks.map((link) => {
              const IconComponent = getIconComponent(link.iconName);
              if (link.children?.length) {
                const isExpanded = expandedSections.has(link.href + link.label);
                const isActiveSection = link.children.some(c => pathname?.startsWith(c.href));
                return (
                  <div key={link.href + link.label} className="space-y-1">
                    {collapsed ? (
                      <Link
                        href={link.href || link.children[0].href}
                        onClick={(event) => void handlePosLinkClick(event, link.href || link.children[0].href)}
                        className={cn('flex items-center gap-3 rounded-lg py-2 text-muted-foreground transition-all hover:text-primary', 'px-1.5 justify-center')}
                      >
                        <IconComponent className="h-4 w-4" />
                      </Link>
                    ) : (
                      <button
                        type="button"
                        onClick={() => toggleSection(link.href + link.label)}
                        className={cn(
                          'flex w-full items-center gap-3 rounded-lg px-3 py-2 transition-all hover:text-primary',
                          isActiveSection ? 'text-primary font-medium' : 'text-foreground',
                        )}
                      >
                        <IconComponent className="h-4 w-4 shrink-0" />
                        <span className="block flex-1 text-start">{link.label}</span>
                        <span className={cn('text-xs transition-transform duration-200', isExpanded ? 'rotate-90' : '')}>›</span>
                      </button>
                    )}
                    {!collapsed && isExpanded && (
                      <div className="ms-5 border-s ps-3 space-y-1">
                        {link.children.map((child) => {
                          const ChildIcon = getIconComponent(child.iconName);
                          return (
                            <Link
                              key={child.href + child.label}
                              href={child.href}
                              onClick={(event) => void handlePosLinkClick(event, child.href)}
                              className={cn(
                                'flex items-center gap-3 rounded-lg px-3 py-2 transition-all hover:text-primary',
                                pathname?.startsWith(child.href) ? 'text-primary font-medium bg-primary/10' : 'text-muted-foreground',
                              )}
                            >
                              <ChildIcon className="h-4 w-4" />
                              <span className="block">{child.label}</span>
                              {resolveLiveBadge(child.href, child.badge) && (
                                <Badge className="ms-auto flex h-6 w-6 shrink-0 items-center justify-center rounded-full">
                                  {resolveLiveBadge(child.href, child.badge)}
                                </Badge>
                              )}
                            </Link>
                          );
                        })}
                      </div>
                    )}
                  </div>
                );
              }
              return (
                <Link
                  key={link.href + link.label}
                  href={link.href}
                  onClick={(event) => void handlePosLinkClick(event, link.href)}
                  className={cn('flex items-center gap-3 rounded-lg py-2 text-muted-foreground transition-all hover:text-primary', collapsed ? 'px-1.5 justify-center' : 'px-3')}
                >
                  <IconComponent className="h-4 w-4" />
                  <span className={navTextClass}>{link.label}</span>
                  {resolveLiveBadge(link.href, link.badge) && (
                    <Badge className={cn('ms-auto h-6 w-6 shrink-0 items-center justify-center rounded-full', badgeClass)}>
                      {resolveLiveBadge(link.href, link.badge)}
                    </Badge>
                  )}
                </Link>
              );
            })}
          </nav>
        </div>
        <div className={cn('border-t py-3', collapsed ? 'px-1' : 'px-4')}>
          <div className={cn('flex items-center gap-2', collapsed ? 'flex-col justify-center' : 'justify-between')}>
            <CompactLanguageSwitcher currentLocale={currentLocale} t={languageT} />
            <DashboardUserMenu
              userName={userName}
              userInitial={userInitial}
              userAvatarUrl={userAvatarUrl}
              userAvatarHint={userAvatarHint}
              settingsLabel={settingsLabel}
              supportLabel={supportLabel}
              logoutLabel={logoutLabel}
            />
          </div>
        </div>
      </div>
    </aside>
  );
}
