'use client';

import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import Link from 'next/link';
import { Badge } from '@/components/ui/badge';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { Button } from '@/components/ui/button';
import { PanelLeft, Building } from 'lucide-react';
import { CompactLanguageSwitcher } from './compact-language-switcher';
import { DashboardUserMenu } from './dashboard-user-menu';
import { getIconComponent } from './icon-map';

interface NavLink {
  href: string;
  label: string;
  iconName: string;
  badge?: number | null;
  children?: NavLink[];
}

export function MobileNavMenu({ 
  navLinks, 
  appName, 
  appLogoUrl,
  isRtl,
  isPos,
  isAdmin,
  employeeCashAccountCode,
  currentLocale,
  languageT,
  userName,
  userInitial,
  userAvatarUrl,
  userAvatarHint,
  settingsLabel,
  supportLabel,
  logoutLabel,
}: { 
  navLinks: NavLink[]; 
  appName: string;
  appLogoUrl?: string;
  isRtl: boolean;
  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 [mounted, setMounted] = useState(false);
  const [open, setOpen] = useState(false);
  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');

  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;
  };

  const handlePosLinkClick = async (event: React.MouseEvent<HTMLAnchorElement>, href: string) => {
    if (href !== '/admin/sales/pos') {
      setOpen(false);
      return;
    }
    event.preventDefault();
    setOpen(false);
    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);
  };

  useEffect(() => {
    setMounted(true);
  }, []);

  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);
    };
  }, []);

  if (isPosPage) {
    return null;
  }

  if (!mounted) {
    return (
      <Button size="icon" variant="outline" className="sm:hidden" disabled aria-hidden="true">
        <PanelLeft className="h-5 w-5" />
      </Button>
    );
  }

  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetTrigger asChild>
        <Button size="icon" variant="outline" className="sm:hidden">
          <PanelLeft className="h-5 w-5" />
          <span className="sr-only">Toggle Menu</span>
        </Button>
      </SheetTrigger>
      <SheetContent side={isRtl ? 'right' : 'left'} className="sm:max-w-xs">
        <div className="flex h-full flex-col">
        <nav className="grid gap-6 text-lg font-medium">
          {(() => {
            const homeHref = isPos ? '/admin/sales/pos' : isAdmin ? '/admin' : '/employee';
            return (
          <Link
            href={homeHref}
            onClick={(event) => void handlePosLinkClick(event, homeHref)}
            className="group flex h-10 w-10 shrink-0 items-center justify-center gap-2 rounded-full bg-primary text-lg font-semibold text-primary-foreground md:text-base"
          >
            {appLogoUrl ? (
              <img src={appLogoUrl} alt={appName} className="h-8 w-auto" />
            ) : (
              <Building className="h-5 w-5 transition-all group-hover:scale-110" />
            )}
            <span className="sr-only">{appName}</span>
          </Link>
            );
          })()}
          {navLinks.map((link) => {
            const IconComponent = getIconComponent(link.iconName);
            if (link.children?.length) {
              return (
                <div key={link.href + link.label} className="space-y-2">
                  <div className="flex items-center gap-4 px-2.5 text-foreground">
                    <IconComponent className="h-5 w-5" />
                    {link.label}
                  </div>
                  <div className="ms-6 grid gap-3 border-s ps-4">
                    {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="flex items-center gap-4 px-2.5 text-muted-foreground hover:text-foreground"
                        >
                          <ChildIcon className="h-5 w-5" />
                          {child.label}
                          {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="flex items-center gap-4 px-2.5 text-muted-foreground hover:text-foreground"
              >
                <IconComponent className="h-5 w-5" />
                {link.label}
                {resolveLiveBadge(link.href, link.badge) && (
                  <Badge className="ms-auto flex h-6 w-6 shrink-0 items-center justify-center rounded-full">
                    {resolveLiveBadge(link.href, link.badge)}
                  </Badge>
                )}
              </Link>
            );
          })}
        </nav>
        <div className="mt-auto border-t pt-4">
          <div className="flex items-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>
      </SheetContent>
    </Sheet>
  );
}
