"use client";
import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useState } from "react";
import logo from "@/assets/icons/logo.svg";
import logoIcon from "@/assets/icons/enizam-logo-icon.svg";
import { ChevronDown, LogOut } from "lucide-react";
import { logout } from "@/redux/slices/user";
import { useAppDispatch } from "@/redux/hooks";
import { DashboardDrawerProps } from "@/types/navigation/drawer";
import { MenuItemProp } from "@/types/navigation/menu";
import { useParams, usePathname } from "next/navigation";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import DataService from "@/config/axios";
import { useComplaintsNotify } from "@/context/complaints-notify-context";
import {
  CLIENT_WORKSPACE_CHANGE_EVENT,
  CLIENT_WORKSPACE_STORAGE_KEY,
} from "@/features/client/constants";
import { getLogoutRedirectPath, getTenantSlugFromLocation, tenantHref } from "@/lib/tenant-routing";

function resolveHref(
  pathname: string,
  app: string | string[] | undefined,
  item: Pick<MenuItemProp, "href" | "fullPath">
) {
  if (!item.href) return "#";
  if (item.fullPath) return String(item.href);
  return tenantHref(pathname, String(item.href), typeof app === "string" ? app : undefined);
}

function pathMatchesItem(
  pathname: string,
  app: string | string[] | undefined,
  item: MenuItemProp
): boolean {
  if (item.children?.length) {
    return item.children.some((child) => pathMatchesItem(pathname, app, child));
  }
  if (!item.href) return false;
  const href = resolveHref(pathname, app, item);
  if (href === "/") return pathname === "/";
  return pathname === href || pathname.startsWith(`${href}/`);
}

const DashboardDrawer = ({
  isMobile,
  menu,
  isOpen,
  toggleDrawer,
}: DashboardDrawerProps) => {
  const dispatch = useAppDispatch();
  const params = useParams();
  const app = params?.app;
  const pathname = usePathname() || "";
  const logoutHref = getLogoutRedirectPath(
    pathname,
    typeof params?.slug === "string" ? params.slug : undefined
  );
  const { unreadCount: complaintsUnread } = useComplaintsNotify();
  const [accounts, setAccounts] = useState<any[]>([]);
  const [activeAccount, setActiveAccount] = useState<any>(null);
  const [isSuperAdmin, setIsSuperAdmin] = useState(false);
  const [adminClients, setAdminClients] = useState<
    { _id: string; name: string; clientId: string; status?: string }[]
  >([]);
  const [sidebarClientKey, setSidebarClientKey] = useState("");
  const [meClient, setMeClient] = useState<{ name: string; clientId: string } | null>(null);
  const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({});

  useEffect(() => {
    const keys: Record<string, boolean> = {};
    for (const item of menu) {
      if (item.children?.length && pathMatchesItem(pathname, app, item)) {
        keys[String(item.name)] = true;
      }
    }
    if (Object.keys(keys).length === 0) return;
    setExpandedGroups((prev) => ({ ...prev, ...keys }));
  }, [menu, pathname, app]);

  useEffect(() => {
    let cancelled = false;
    const fetchAccounts = async () => {
      try {
        const [accountsRes, meRes] = await Promise.all([
          DataService.get("/accounts/list"),
          DataService.get("/user/me"),
        ]);
        if (cancelled) return;
        const rows = accountsRes?.data?.data;
        if (Array.isArray(rows) && rows.length > 0) {
          setAccounts(rows);
          setActiveAccount(rows[0]);
        }
        const me = meRes?.data?.data as
          | { type?: string; client?: { name?: string; clientId?: string } | null }
          | undefined;
        const superAdmin = me?.type === "super_admin";
        setIsSuperAdmin(superAdmin);
        if (!superAdmin) {
          const clientName = me?.client?.name?.trim() || "";
          const clientId = me?.client?.clientId?.trim() || "";
          setMeClient(clientName && clientId ? { name: clientName, clientId } : null);
          setSidebarClientKey(clientId || "");
        }
        if (superAdmin) {
          const clientsRes = await DataService.get("/admin/clients");
          if (cancelled) return;
          const clients = Array.isArray(clientsRes?.data?.data) ? clientsRes.data.data : [];
          setAdminClients(clients);
          let stored = "";
          try {
            stored = sessionStorage.getItem(CLIENT_WORKSPACE_STORAGE_KEY) || "";
          } catch {
            stored = "";
          }
          const validStored = stored && clients.some((c: { clientId: string }) => c.clientId === stored);
          setSidebarClientKey(validStored ? stored : clients[0]?.clientId || "");
        }
      } catch {
        /* 401/403 if token missing or invalid, or API error — sidebar must still render */
        if (!cancelled) {
          setAccounts([]);
          setActiveAccount(null);
          setIsSuperAdmin(false);
          setAdminClients([]);
          setSidebarClientKey("");
          setMeClient(null);
        }
      }
    };
    fetchAccounts();
    return () => {
      cancelled = true;
    };
  }, []);

  const handleLogout = () => {
    dispatch(logout());
  };

  const handleSidebarClientChange = (clientKey: string) => {
    setSidebarClientKey(clientKey);
    try {
      sessionStorage.setItem(CLIENT_WORKSPACE_STORAGE_KEY, clientKey);
    } catch {
      /* ignore */
    }
    window.dispatchEvent(
      new CustomEvent(CLIENT_WORKSPACE_CHANGE_EVENT, {
        detail: { clientKey },
      })
    );
  };

  const toggleGroup = (name: string) => {
    setExpandedGroups((prev) => ({ ...prev, [name]: !prev[name] }));
  };

  const renderLeafLink = (item: MenuItemProp, nested = false) => {
    const href = resolveHref(pathname, app, item);
    const isComplaints = String(item.href) === "/complaints" && !item.fullPath;
    const showUnreadDot = isComplaints && complaintsUnread > 0;
    const isActive = pathMatchesItem(pathname, app, item);
    return (
      <Link
        key={`${String(item.name)}-${String(item.href)}`}
        href={href}
        target={item.openInNewTab ? "_blank" : undefined}
        rel={item.openInNewTab ? "noopener noreferrer" : undefined}
        title={showUnreadDot ? "Unread complaints" : String(item.name)}
        className={`flex items-center rounded-lg hover:bg-primary hover:text-white ${
          isActive ? "bg-primary/10 text-primary" : ""
        } ${
          nested
            ? isOpen
              ? "gap-3 py-2 pl-10 pr-3"
              : "justify-center py-2 px-1 !size-9"
            : isOpen
              ? "gap-3 p-3"
              : "justify-center py-3 px-1 !size-10"
        } text-sm`}
      >
        <span className="relative inline-flex shrink-0">
          {item.icon}
          {showUnreadDot ? (
            <span
              className="absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full bg-red-500 ring-2 ring-white"
              aria-hidden
            />
          ) : null}
        </span>
        {isOpen ? <span className="min-w-0 flex-1 truncate">{item.name}</span> : null}
      </Link>
    );
  };

  const renderMenuItem = (item: MenuItemProp) => {
    const children = item.children;
    if (!children?.length) {
      return renderLeafLink(item);
    }

    const groupKey = String(item.name);
    const isExpanded = Boolean(expandedGroups[groupKey]);
    const primaryHref = resolveHref(pathname, app, item);
    const groupActive = pathMatchesItem(pathname, app, item);

    if (!isOpen) {
      return (
        <Link
          key={groupKey}
          href={primaryHref}
          title={groupKey}
          className={`flex items-center justify-center rounded-lg hover:bg-primary hover:text-white py-3 px-1 !size-10 text-sm ${
            groupActive ? "bg-primary/10 text-primary" : ""
          }`}
        >
          {item.icon}
        </Link>
      );
    }

    return (
      <div key={groupKey} className="flex flex-col gap-1">
        <button
          type="button"
          onClick={() => toggleGroup(groupKey)}
          className={`flex w-full items-center gap-3 rounded-lg p-3 text-sm hover:bg-primary hover:text-white ${
            groupActive ? "bg-primary/10 text-primary" : ""
          }`}
          aria-expanded={isExpanded}
        >
          <span className="inline-flex shrink-0">{item.icon}</span>
          <span className="min-w-0 flex-1 truncate text-left">{item.name}</span>
          <ChevronDown
            className={`size-4 shrink-0 transition-transform ${isExpanded ? "rotate-180" : ""}`}
          />
        </button>
        {isExpanded
          ? children.map((child) => renderLeafLink(child, true))
          : null}
      </div>
    );
  };

  return (
    <>
      <div
        className={`dashboard-drawer ${
          isMobile && !isOpen ? "hidden" : isOpen ? " w-64" : "w-20"
        }`}
      >
        <div className="flex h-full min-h-0 flex-col p-4">
          <div
            className={`flex ${
              isOpen ? "flex-row" : "flex-col"
            } shrink-0 gap-4 justify-between items-center w-full mt-3 mb-5`}
          >
            {isOpen ? (
              <Link href="/" title="Nizamify home" className="block w-2/3">
                <Image
                  src={logo}
                  alt="Nizamify"
                  width={500}
                  height={500}
                  className="h-auto w-full"
                />
              </Link>
            ) : (
              <Link href="/" title="Nizamify home" className="flex justify-center">
                <Image
                  src={logoIcon}
                  alt="Nizamify"
                  width={44}
                  height={47}
                  className="h-8 w-auto"
                />
              </Link>
            )}
          </div>
          <div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
            {accounts.length > 0 ? (
              <Select
                value={activeAccount?.accountId ?? ""}
                onValueChange={(value) => {
                  const account = accounts.find(
                    (account) => account.accountId === value
                  );
                  if (account) {
                    setActiveAccount(account);
                  }
                }}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select account" />
                </SelectTrigger>
                <SelectContent>
                  {accounts.map((account) => (
                    <SelectItem key={account._id} value={account.accountId}>
                      {account.accountName ?? "Enizam"}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            ) : null}
            { (String(app) === "client" ||
              String(app) === "property" ||
              Boolean(getTenantSlugFromLocation(pathname))) &&
            ((isSuperAdmin && adminClients.length > 0) || (!isSuperAdmin && meClient)) ? (
              <Select
                value={sidebarClientKey}
                onValueChange={(value) => {
                  if (!isSuperAdmin) return;
                  handleSidebarClientChange(value);
                }}
                disabled={!isSuperAdmin}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select client" />
                </SelectTrigger>
                <SelectContent>
                  {isSuperAdmin
                    ? adminClients.map((client) => (
                        <SelectItem key={client._id} value={client.clientId}>
                          {client.name}
                        </SelectItem>
                      ))
                    : meClient && (
                        <SelectItem value={meClient.clientId}>{meClient.name}</SelectItem>
                      )}
                </SelectContent>
              </Select>
            ) : null}
            <div
              className={`flex flex-col gap-2 pb-4 text-black text-lg ${
                !isOpen && "items-center"
              }`}
            >
              {menu.map((item, index) => {
                const section = item.section?.trim() || "";
                const prevSection = index > 0 ? menu[index - 1].section?.trim() || "" : "";
                const showSection = Boolean(isOpen && section && section !== prevSection);
                return (
                  <React.Fragment key={`${String(item.name)}-${String(item.href ?? index)}`}>
                    {showSection ? (
                      <div
                        className={`px-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground ${
                          index > 0 ? "pt-3" : "pt-1"
                        }`}
                      >
                        {section}
                      </div>
                    ) : null}
                    {renderMenuItem(item)}
                  </React.Fragment>
                );
              })}
              <Link
                href={logoutHref}
                className={`flex items-center rounded-lg text-red-600 hover:bg-red-100 ${
                  isOpen ? "p-3" : "py-3 px-1 justify-center !size-8"
                } gap-3 text-sm`}
                onClick={handleLogout}
              >
                <LogOut className="size-5" />
                {isOpen && "Logout"}
              </Link>
            </div>
          </div>
        </div>
      </div>
      {isMobile && isOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-10"
          onClick={toggleDrawer}
        ></div>
      )}
    </>
  );
};

export default DashboardDrawer;
