"use client"

import * as React from "react"
import { CopyIcon, HomeIcon, SettingsIcon, UsersIcon, UtensilsIcon, LayoutGridIcon, ChefHatIcon, ShoppingCartIcon, PackageSearchIcon, TruckIcon, CalculatorIcon, ContactIcon, BanknoteIcon, BellIcon, GlobeIcon, MapPinIcon, ChevronLeftIcon, CalendarDaysIcon, ShieldAlertIcon, LockIcon, LayoutTemplateIcon } from "lucide-react"
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  useSidebar
} from "@/components/ui/sidebar"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { NavUser } from "@/components/nav-user"
import { usePathname } from "next/navigation"
import { ThemeToggle } from "@/components/theme-toggle"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { getMyMessages, getUnreadMessagesCount, markMessageRead } from "@/app/actions/messages"
import { format } from "date-fns-jalali"
import Link from "next/link"

type NavItem = {
  title: string;
  url?: string;
  icon: React.ReactNode;
  standalone?: boolean;
  feature?: string;
  customClass?: string;
  iconClass?: string;
  items?: { title: string; url: string; feature?: string }[];
};

const data = {
  user: {
    name: "مدیر توکان",
    email: "admin@tukan.ir",
    avatar: "",
  },
  navMain: [
    { title: "داشبورد", url: "/", icon: <HomeIcon className="w-4 h-4" />, standalone: true, feature: "DASHBOARD" },
    { title: "سفارشات", url: "/orders", icon: <ShoppingCartIcon className="w-4 h-4" />, standalone: true, feature: "ORDERS" },
    { 
      title: "محصولات", 
      icon: <PackageSearchIcon className="w-4 h-4" />, 
      feature: "PRODUCTS",
      items: [
        { title: "لیست محصولات", url: "/products" },
        { title: "دسته‌بندی‌ها", url: "/categories" },
        { title: "ویژگی‌ها", url: "/attributes" },
        { title: "برندها", url: "/brands" },
        { title: "نظرات کاربران", url: "/reviews" },
      ] 
    },
    { title: "رسانه‌ها", url: "/media", icon: <PackageSearchIcon className="w-4 h-4" />, standalone: true, feature: "MEDIA" },
    { title: "مشتریان", url: "/customers", icon: <ContactIcon className="w-4 h-4" />, standalone: true, feature: "CUSTOMERS" },
    { 
      title: "حسابداری و مالی", 
      icon: <CalculatorIcon className="w-4 h-4" />, 
      feature: "ACCOUNTING",
      items: [
        { title: "صندوق‌ها و حساب‌ها", url: "/accounting/accounts" },
        { title: "تراکنش‌ها", url: "/accounting/transactions" },
        { title: "چک‌ها", url: "/accounting/cheques" },
        { title: "تأمین‌کنندگان", url: "/suppliers" },
        { title: "فاکتورهای خرید", url: "/purchases" },
        { title: "گزارشات و سود و زیان", url: "/accounting/reports" },
      ]
    },
    { title: "صندوق فروش (POS)", url: "/pos", icon: <ShoppingCartIcon className="w-4 h-4" />, standalone: true, feature: "POS", customClass: "text-emerald-700 dark:text-emerald-400", iconClass: "text-emerald-600 dark:text-emerald-400" },
    { title: "سایت ساز توکان", url: "/storefront", icon: <LayoutTemplateIcon className="w-4 h-4" />, standalone: true, feature: "STOREFRONT" },
    { title: "پرسنل", url: "/users", icon: <UsersIcon className="w-4 h-4" />, standalone: true, feature: "STAFF" },
    { title: "روش‌های ارسال", url: "/shipping", icon: <TruckIcon className="w-4 h-4" />, standalone: true, feature: "LOGISTICS" },
    { title: "تنظیمات", url: "/settings", icon: <SettingsIcon className="w-4 h-4" />, standalone: true, feature: "SETTINGS" },
  ] as NavItem[],
}

const MENU_ACCESS: Record<string, string[]> = {
  ADMIN: ["/", "/orders", "/products", "/categories", "/attributes", "/brands", "/reviews", "/customers", "/users", "/settings", "/audit", "/media", "/accounting/accounts", "/accounting/transactions", "/accounting/cheques", "/accounting/reports", "/suppliers", "/purchases", "/pos", "/storefront", "/shipping"],
  ACCOUNTANT: ["/", "/customers"],
  CASHIER: ["/", "/customers"],
  SELLER: ["/"],
  DELIVERY: ["/"],
  CHEF: ["/"],
  ASSISTANT_CHEF: ["/"],
  WORKER: ["/"],
};

const ROLE_MAP: Record<string, string> = {
  ADMIN: "مدیر سیستم",
  CASHIER: "صندوق‌دار",
  SELLER: "فروشنده",
  ACCOUNTANT: "حسابدار",
  DELIVERY: "پیک",
  CHEF: "تأمین‌کننده",
  ASSISTANT_CHEF: "کمک تأمین‌کننده",
  WORKER: "کارگر",
};

export function AppSidebar({ user: sessionUser, onlineServerUrl, settings, ...props }: React.ComponentProps<typeof Sidebar> & { user?: any, onlineServerUrl?: string | null, settings?: any }) {
  const pathname = usePathname();
  const { setOpenMobile } = useSidebar();

  // Parse allowed features from settings (JSON string from Hub JWT)
  const allowedFeatures: string[] = React.useMemo(() => {
    if (!settings?.allowedFeatures) return []; // No plan data yet — no restriction  
    try { return JSON.parse(settings.allowedFeatures); } catch { return []; }
  }, [settings?.allowedFeatures]);

  const isLocalhost = typeof window !== 'undefined' && (
    window.location.hostname === 'localhost' ||
    window.location.hostname === '127.0.0.1'
  );

  // Returns true if user has plan access to this feature
  const hasPlanAccess = (featureKey?: string): boolean => {
    if (!featureKey) return true; // No feature key = always accessible
    if (isLocalhost) return true; // Localhost is always unrestricted
    if (allowedFeatures.length === 0) return true; // No plan data yet = unrestricted
    return allowedFeatures.includes(featureKey);
  };

  const navItems: NavItem[] = sessionUser?.role === "ADMIN" && !data.navMain.some(n => n.url === "/audit")
    ? [...data.navMain, { title: "لاگ سیستم", url: "/audit", icon: <ShieldAlertIcon className="w-4 h-4 text-rose-500" />, standalone: true, feature: "AUDIT_LOG" }]
    : data.navMain;

  const [messages, setMessages] = React.useState<any[]>([]);
  const [unreadCount, setUnreadCount] = React.useState(0);
  const [isMessagesOpen, setIsMessagesOpen] = React.useState(false);
  const [openMenu, setOpenMenu] = React.useState<string | null>(null);

  React.useEffect(() => {
    if (sessionUser) {
      getUnreadMessagesCount().then((c: number) => setUnreadCount(c));
    }
  }, [sessionUser]);

  React.useEffect(() => {
    // Automatically open the parent menu that has an active child
    const activeParent = data.navMain.find(item => item.items && item.items.some((sub: any) => pathname.startsWith(sub.url)));
    if (activeParent) {
      setOpenMenu(activeParent.title);
    }
  }, [pathname]);

  const handleOpenMessages = async (open: boolean) => {
    setIsMessagesOpen(open);
    if (open) {
      const msgs = await getMyMessages();
      setMessages(msgs);
    }
  };

  const handleMarkAsRead = async (id: string) => {
    await markMessageRead(id);
    setMessages(messages.map(m => m.id === id ? { ...m, isRead: true } : m));
    setUnreadCount(Math.max(0, unreadCount - 1));
  };

  const role = sessionUser?.role || "SELLER";
  const allowedPaths = MENU_ACCESS[role] || MENU_ACCESS["SELLER"];

  // Evaluate role access for a given navigation group or item
  const hasRoleAccess = (item: any) => {
    if (item.standalone && item.url) return allowedPaths.includes(item.url);
    if (item.items) return item.items.some((sub: any) => allowedPaths.includes(sub.url));
    return false;
  };

  // Evaluate combined role + plan access
  const hasAccessToItem = (item: any) => {
    if (!hasRoleAccess(item)) return false;
    // For standalone items — check plan (but still show as locked)
    return true; // We show all role-accessible items; locked ones show with lock icon
  };

  const isNavActive = (item: any) => {
    if (item.standalone && item.url) {
      if (item.url === "/") return pathname === "/";
      if (item.url === "/orders" && pathname.startsWith("/orders/pos")) return false;
      return pathname.startsWith(item.url);
    }
    if (item.items) {
      return item.items.some((sub: any) => pathname.startsWith(sub.url));
    }
    return false;
  };

  const displayUser = sessionUser ? {
    name: sessionUser.name || sessionUser.username,
    email: ROLE_MAP[role] || "مدیر توکان",
    avatar: sessionUser.avatarUrl || "",
  } : data.user;

  return (
    <Sidebar side="right" {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem className="flex items-center gap-1 w-full relative">
            <SidebarMenuButton size="lg" asChild className="flex-1">
              <Link href="/" onClick={() => setOpenMobile(false)}>
                <div className="flex aspect-square size-8 items-center justify-center rounded-lg shadow-sm bg-transparent overflow-hidden object-contain">
                  <img src="/favicon.ico" alt="Tukan Logo" className="w-full h-full object-contain drop-shadow-sm" />
                </div>
                <div className="grid flex-1 text-right text-sm leading-tight mr-2">
                  <span className="truncate font-bold text-base">سیستم مدیریت توکان</span>
                  <span className="truncate text-xs text-muted-foreground">نسخه فروشگاه ساز - بتا ۱</span>
                </div>
              </Link>
            </SidebarMenuButton>
            <div className="absolute left-2">
              <ThemeToggle />
            </div>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>

      <SidebarContent>
        <SidebarMenu className="px-3 mt-4 space-y-1.5 flex-1">
          {navItems.map((item) => {
            if (!hasAccessToItem(item)) return null;
            const isPlanLocked = item.feature && !hasPlanAccess(item.feature);

            if (item.standalone) {
              return (
                <SidebarMenuItem key={item.title}>
                  <SidebarMenuButton
                    asChild
                    tooltip={isPlanLocked ? `ارتقا به پلن بالاتر برای دسترسی به «${item.title}»` : item.title}
                    className={`py-5 group/navitem transition-colors rounded-xl font-medium ${isPlanLocked
                        ? 'opacity-50 cursor-not-allowed'
                        : item.customClass || ''
                      }`}
                    isActive={!isPlanLocked && isNavActive(item)}
                  >
                    {isPlanLocked ? (
                      <div className="flex items-center gap-3 w-full" title="نیاز به ارتقا پلن">
                        <div className="transition-transform duration-300">{item.icon}</div>
                        <span className="text-sm tracking-tight flex-1">{item.title}</span>
                        <LockIcon className="w-3 h-3 text-muted-foreground shrink-0" />
                      </div>
                    ) : (
                      <Link href={item.url as string} className="flex items-center gap-3" onClick={() => setOpenMobile(false)}>
                        <div className={`transition-transform duration-300 group-hover/navitem:scale-110 ${!item.iconClass ? 'group-hover/navitem:text-indigo-500' : item.iconClass}`}>
                          {item.icon}
                        </div>
                        <span className={`text-sm tracking-tight ${!item.iconClass ? 'group-hover/navitem:text-indigo-600' : item.iconClass}`}>{item.title}</span>
                      </Link>
                    )}
                  </SidebarMenuButton>
                </SidebarMenuItem>
              );
            }

            // Render Collapsible Menu
            const isActive = isNavActive(item);
            const allSubLocked = item.items?.every((sub: any) => sub.feature && !hasPlanAccess(sub.feature));
            return (
              <Collapsible
                key={item.title}
                open={openMenu === item.title}
                onOpenChange={(isOpen) => setOpenMenu(isOpen ? item.title : null)}
                className="group/collapsible"
              >
                <SidebarMenuItem>
                  <CollapsibleTrigger asChild>
                    <SidebarMenuButton className={`py-5 group/navitem rounded-xl font-medium transition-colors w-full flex items-center justify-between ${isActive ? 'bg-indigo-50/50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-300' : 'hover:bg-muted/80'} ${allSubLocked ? 'opacity-60' : ''}`}>
                      <div className="flex items-center gap-3 flex-1">
                        <div className={`transition-transform duration-300 group-hover/navitem:scale-110 ${isActive ? 'text-indigo-600 dark:text-indigo-400' : 'text-muted-foreground group-hover/navitem:text-indigo-500'}`}>
                          {item.icon}
                        </div>
                        <span className={`text-sm tracking-tight pr-1 text-right ${isActive ? '' : 'group-hover/navitem:text-indigo-600'}`}>{item.title}</span>
                      </div>
                      <ChevronLeftIcon className={`w-4 h-4 transition-transform duration-300 ${isActive ? '-rotate-90 text-indigo-500' : 'group-data-[state=open]/collapsible:-rotate-90 opacity-50'}`} />
                    </SidebarMenuButton>
                  </CollapsibleTrigger>
                  <CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down transition-all">
                    <SidebarMenuSub className="mr-4 ml-0 pr-2 border-r border-l-0 border-border/50 space-y-1 my-1">
                      {item.items?.map((sub) => {
                        if (!allowedPaths.includes(sub.url)) return null;
                        const isSubLocked = sub.feature && !hasPlanAccess(sub.feature);
                        const isSubActive = !isSubLocked && pathname.startsWith(sub.url);
                        return (
                          <SidebarMenuSubItem key={sub.title}>
                            <SidebarMenuSubButton
                              asChild={!isSubLocked}
                              isActive={isSubActive}
                              className={`rounded-lg py-1.5 transition-colors font-medium text-[13px] ${isSubActive ? 'bg-indigo-100/50 dark:bg-indigo-500/20 text-indigo-700 dark:text-indigo-300 font-bold' : ''} ${isSubLocked ? 'opacity-50 cursor-not-allowed' : ''}`}
                            >
                              {isSubLocked ? (
                                <div className="flex items-center justify-between w-full px-2" title="نیاز به ارتقا پلن">
                                  <span>{sub.title}</span>
                                  <LockIcon className="w-3 h-3 text-muted-foreground" />
                                </div>
                              ) : (
                                <Link href={sub.url} onClick={() => setOpenMobile(false)}>
                                  <span className={isSubActive ? 'pr-1' : ''}>{sub.title}</span>
                                </Link>
                              )}
                            </SidebarMenuSubButton>
                          </SidebarMenuSubItem>
                        );
                      })}
                    </SidebarMenuSub>
                  </CollapsibleContent>
                </SidebarMenuItem>
              </Collapsible>
            );
          })}
        </SidebarMenu>
      </SidebarContent>

      <SidebarFooter>
        <SidebarMenu className="px-3">
          <SidebarMenuItem>
            <Dialog open={isMessagesOpen} onOpenChange={handleOpenMessages}>
              <DialogTrigger asChild>
                <SidebarMenuButton className="mb-1 text-rose-500 hover:text-rose-600 hover:bg-rose-50 font-bold transition-colors cursor-pointer rounded-xl py-5">
                  <div className="relative shrink-0">
                    <BellIcon className="w-5 h-5" />
                    {unreadCount > 0 && <span className="absolute -top-1 -right-1 w-3.5 h-3.5 flex items-center justify-center rounded-full bg-rose-500 shadow-[0_0_5px_#f43f5e] text-[8px] text-white animate-pulse">{unreadCount}</span>}
                  </div>
                  <span>پیام‌ها و اعلانات</span>
                </SidebarMenuButton>
              </DialogTrigger>
              <DialogContent className="sm:max-w-md max-w-[90vw]">
                <DialogHeader>
                  <DialogTitle className="flex items-center gap-2 px-2">
                    <BellIcon className="w-5 h-5 text-rose-500" />
                    پیام‌های سیستمی شما
                  </DialogTitle>
                </DialogHeader>
                <div className="py-2 flex flex-col gap-2 max-h-[60vh] overflow-y-auto no-scrollbar px-2">
                  {messages.length === 0 ? (
                    <div className="flex flex-col items-center justify-center text-muted-foreground opacity-50 py-10">
                      <BellIcon className="w-12 h-12 mb-4 opacity-50" />
                      <p>هیچ پیامی برای شما وجود ندارد.</p>
                    </div>
                  ) : (
                    messages.map(msg => (
                      <div key={msg.id} className={`p-4 rounded-xl border flex flex-col gap-1 transition-colors ${msg.isRead ? 'bg-muted/30 border-muted' : 'bg-rose-50/50 border-rose-200 shadow-sm'}`}>
                        <div className="flex justify-between items-center text-xs">
                          <span className="font-bold text-primary">{msg.sender?.fullName || msg.sender?.username || 'سیستم'}</span>
                          <span className="text-muted-foreground font-sans tracking-tight opacity-70" dir="ltr">{format(new Date(msg.createdAt), 'yyyy/MM/dd HH:mm')}</span>
                        </div>
                        <p className="text-sm mt-2 font-medium">{msg.content}</p>
                        {!msg.isRead && (
                          <button type="button" onClick={() => handleMarkAsRead(msg.id)} className="text-[10px] text-rose-600 bg-rose-100 px-3 py-1 font-bold rounded ml-auto mt-3 hover:bg-rose-200 transition-colors">
                            علامت به عنوان خوانده شده
                          </button>
                        )}
                      </div>
                    ))
                  )}
                </div>
              </DialogContent>
            </Dialog>
          </SidebarMenuItem>
          {onlineServerUrl && (
            <SidebarMenuItem>
              <SidebarMenuButton asChild className="mb-1 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 font-bold transition-colors cursor-pointer rounded-xl py-5">
                <a href={onlineServerUrl} target="_blank" rel="noopener noreferrer">
                  <GlobeIcon className="w-5 h-5" />
                  <span>نمایش نسخه آنلاین</span>
                </a>
              </SidebarMenuButton>
            </SidebarMenuItem>
          )}
        </SidebarMenu>
        <NavUser user={displayUser} />
      </SidebarFooter>
    </Sidebar>
  )
}
