"use client";

import {
  BarChart3Icon,
  Building2Icon,
  ChevronRightIcon,
  FoldersIcon,
  LayoutTemplateIcon,
  Loader2,
  MessageCircle,
  MessageSquareTextIcon,
  PlusIcon,
  SettingsIcon,
  UserIcon,
  WorkflowIcon,
} from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState, useTransition } from "react";
import { useTranslation } from "react-i18next";
import { TOrganizationRole } from "@formbricks/types/memberships";
import { TOrganization } from "@formbricks/types/organizations";
import { TUser } from "@formbricks/types/user";
import {
  getOrganizationsForSwitcherAction,
  getWorkspacesForSwitcherAction,
} from "@/app/(app)/workspaces/[workspaceId]/actions";
import { MainNavigationHeader } from "@/app/(app)/workspaces/[workspaceId]/components/MainNavigationHeader";
import { MainNavigationNotices } from "@/app/(app)/workspaces/[workspaceId]/components/MainNavigationNotices";
import { NavigationLink } from "@/app/(app)/workspaces/[workspaceId]/components/NavigationLink";
import { SettingsSidebarContent } from "@/app/(app)/workspaces/[workspaceId]/components/SettingsSidebarContent";
import { useLatestStableRelease } from "@/app/(app)/workspaces/[workspaceId]/lib/use-latest-stable-release";
import { cn } from "@/lib/cn";
import { readLocalStorage, writeLocalStorage } from "@/lib/localStorage";
import { getBillingFallbackPath } from "@/lib/membership/navigation";
import { getAccessFlags } from "@/lib/membership/utils";
import {
  SWITCHER_DROPDOWN_CONTENT_CLASS_NAME,
  SwitcherDropdownBody,
} from "@/modules/settings/components/switcher-dropdown-body";
import { UserDropdown } from "@/modules/settings/components/user-dropdown";
import { useSwitcherData } from "@/modules/settings/hooks/use-switcher-data";
import { getOrganizationSwitchPath, getWorkspaceHomePath } from "@/modules/settings/lib/organization-switch";
import { Badge } from "@/modules/ui/components/badge";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/modules/ui/components/dropdown-menu";
import { GoBackButton } from "@/modules/ui/components/go-back-button";
import { ModalButton } from "@/modules/ui/components/upgrade-prompt";
import { CreateWorkspaceModal } from "@/modules/workspaces/components/create-workspace-modal";
import { WorkspaceLimitModal } from "@/modules/workspaces/components/workspace-limit-modal";

interface NavigationProps {
  user: TUser;
  organization: TOrganization;
  workspace: { id: string; name: string };
  isFormbricksCloud: boolean;
  isDevelopment: boolean;
  membershipRole?: TOrganizationRole;
  organizationWorkspacesLimit: number;
  isLicenseActive: boolean;
  isNoLicense: boolean;
  isAccessControlAllowed: boolean;
  responseCount: number;
  isFormbricksSurveysConfigured: boolean;
  // Whole days left in the trial, or null when there is no trial to count down. Computed by the
  // server layout: deriving it here would mean reading `Date.now()` during render, which diverges
  // between the server pass and hydration and then goes stale as the tab sits open (ENG-2366).
  trialDaysRemaining: number | null;
  // The workspace's Creatives access is `full` or `windDown` (ENG-6602). Hidden otherwise, with no
  // upgrade notice: Creatives doesn't exist for that workspace.
  isCreativesVisible: boolean;
}

/**
 * A nav section header carrying a Beta badge.
 *
 * Act is still a pre-1.0 surface, and the badge is what tells someone the difference between
 * "this is finished" and "this is early". Analyze graduated out of beta and no longer carries it.
 */
const sectionLabelWithBeta = (label: React.ReactNode) => (
  <span className="inline-flex items-center gap-2">
    <span>{label}</span>
    <Badge
      text="Beta"
      type="gray"
      size="tiny"
      className="text-[10px] font-semibold tracking-normal normal-case"
    />
  </span>
);

/**
 * The text half of a sidebar switcher trigger: name, caption, an in-flight spinner and the chevron.
 *
 * Both switchers rendered this inline and identically, at the deepest nesting in the component —
 * which is most of what pushed MainNavigation past Sonar's cognitive-complexity limit (ENG-3076).
 * Deliberately not wrapping the `<button>` itself: that is a Radix `asChild` target, and moving it
 * behind a component would mean forwarding props and refs by hand for no gain.
 */
const SwitcherTriggerLabel = ({
  isCollapsed,
  isTextVisible,
  isPending,
  name,
  caption,
}: Readonly<{
  isCollapsed: boolean;
  isTextVisible: boolean;
  isPending: boolean;
  name: string;
  caption: string;
}>) => {
  // Collapsed, only the icon shows; `isTextVisible` is the 150ms delay that keeps the label from
  // flashing while the sidebar animates.
  if (isCollapsed || isTextVisible) {
    return null;
  }

  return (
    <>
      <div className="grow overflow-hidden">
        <p className="truncate text-sm font-bold text-slate-700">{name}</p>
        <p className="text-sm text-slate-500">{caption}</p>
      </div>
      {isPending && <Loader2 className="size-4 animate-spin text-slate-600" strokeWidth={1.5} />}
      <ChevronRightIcon className="size-4 shrink-0 text-slate-600" strokeWidth={1.5} />
    </>
  );
};

export const MainNavigation = ({
  organization,
  user,
  workspace,
  membershipRole,
  isFormbricksCloud,
  isDevelopment,
  organizationWorkspacesLimit,
  isLicenseActive,
  isNoLicense,
  isAccessControlAllowed,
  responseCount,
  isFormbricksSurveysConfigured,
  trialDaysRemaining,
  isCreativesVisible,
}: Readonly<NavigationProps>) => {
  const router = useRouter();
  const pathname = usePathname();
  const { t } = useTranslation();
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isTextVisible, setIsTextVisible] = useState(true);

  const [isPending, startTransition] = useTransition();
  const { isManager, isOwner, isBilling, isDashboardViewer } = getAccessFlags(membershipRole);
  const isMembershipPending = membershipRole === undefined;
  const disabledNavigationMessage = isMembershipPending
    ? t("common.loading")
    : t("common.you_are_not_authorized_to_perform_this_action");

  const isOwnerOrManager = isManager || isOwner;
  const latestVersion = useLatestStableRelease(isOwnerOrManager);
  const isSettingsMode = pathname?.includes("/settings");

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
    writeLocalStorage("isMainNavCollapsed", isCollapsed ? "false" : "true");
  };

  useEffect(() => {
    const isCollapsedValueFromLocalStorage = readLocalStorage("isMainNavCollapsed") === "true";
    // eslint-disable-next-line react/set-state-in-effect -- localStorage exists only after hydration; the server renders the expanded default
    setIsCollapsed(isCollapsedValueFromLocalStorage);
  }, []);

  useEffect(() => {
    const toggleTextOpacity = () => {
      setIsTextVisible(isCollapsed);
    };
    const timeoutId = setTimeout(toggleTextOpacity, 150);
    return () => clearTimeout(timeoutId);
  }, [isCollapsed]);

  // Billing and Dashboard viewer both lose most of the navigation, differently on purpose (U17). Billing
  // keeps the items disabled with a tooltip: it is a full organization member whose access is paused
  // while it only manages billing, and the greyed items say what the organization has. A Dashboard viewer
  // never had any of it — no route behind those items is reachable for it (ADR-0025) — so they are hidden,
  // and a section left with nothing loses its header too.
  const mainNavigationSections = useMemo(
    () => [
      {
        id: "ask",
        // Product section (IA) label — intentionally not localized (kept in English across all locales)
        name: "Ask",
        items: [
          {
            name: t("common.surveys"),
            href: `/workspaces/${workspace.id}/surveys`,
            icon: MessageCircle,
            isActive: pathname?.includes("/surveys"),
            isHidden: isDashboardViewer,
            disabled: isMembershipPending || isBilling,
          },
          {
            name: t("common.creatives"),
            href: `/workspaces/${workspace.id}/creatives`,
            icon: LayoutTemplateIcon,
            isActive: pathname?.includes("/creatives"),
            isHidden: !isCreativesVisible || isDashboardViewer,
            disabled: isMembershipPending || isBilling,
          },
          {
            href: `/workspaces/${workspace.id}/contacts`,
            name: t("common.contacts"),
            icon: UserIcon,
            isActive:
              pathname?.includes("/contacts") ||
              pathname?.includes("/segments") ||
              pathname?.includes("/attributes"),
            isHidden: isDashboardViewer,
            disabled: isMembershipPending || isBilling,
          },
        ],
      },
      {
        id: "unify-feedback",
        // Same policy as "Ask" above: product section labels stay English in every locale.
        // Was "Unify" until ENG-2742 settled on Ask / Analyze / Act as the three pillars.
        name: "Analyze",
        items: [
          {
            name: t("workspace.unify.feedback_data"),
            href: `/workspaces/${workspace.id}/unify/sources`,
            icon: MessageSquareTextIcon,
            isActive: pathname?.includes("/unify/"),
            isHidden: isDashboardViewer,
            disabled: isMembershipPending || isBilling,
          },
          {
            // A Dashboard viewer has Dashboards and nothing else of Analysis (ADR-0025).
            name: isDashboardViewer ? t("common.dashboards") : t("common.analysis"),
            href: `/workspaces/${workspace.id}/dashboards`,
            icon: BarChart3Icon,
            isActive: pathname?.includes("/dashboards") || pathname?.includes("/charts"),
            isHidden: false,
            disabled: isMembershipPending || isBilling,
          },
        ],
      },
      {
        id: "act",
        // Kept translated, unlike "Ask" and "Analyze" above. Those two are deliberately English in
        // every locale; this one has been going through t() since it was added. Making the three
        // consistent means dropping a string 15 locales already translate, which is a naming
        // decision rather than a side effect of adding a badge — see ENG-2742.
        name: sectionLabelWithBeta(t("common.act")),
        items: [
          {
            name: t("common.workflows"),
            href: `/workspaces/${workspace.id}/workflows`,
            icon: WorkflowIcon,
            isActive: pathname?.startsWith(`/workspaces/${workspace.id}/workflows`),
            isHidden: isDashboardViewer,
            disabled: isMembershipPending || isBilling,
          },
        ],
      },
    ],
    [t, workspace.id, pathname, isMembershipPending, isBilling, isCreativesVisible, isDashboardViewer]
  );

  // A section whose items are all hidden (Ask and Act for a Dashboard viewer) loses its header too.
  const visibleNavigationSections = mainNavigationSections.filter((section) =>
    section.items.some((item) => !item.isHidden)
  );

  const settingsNavigationItem = useMemo(
    () => ({
      name: t("common.settings"),
      href: `/workspaces/${workspace.id}/settings/workspace/general`,
      icon: SettingsIcon,
      isActive: isSettingsMode,
      disabled: isMembershipPending || isBilling,
    }),
    [t, workspace.id, isSettingsMode, isMembershipPending, isBilling]
  );

  const [isWorkspaceDropdownOpen, setIsWorkspaceDropdownOpen] = useState(false);
  const [isOrganizationDropdownOpen, setIsOrganizationDropdownOpen] = useState(false);
  const workspaceSwitcher = useSwitcherData(
    () => getWorkspacesForSwitcherAction({ organizationId: organization.id }),
    t("common.failed_to_load_workspaces"),
    undefined,
    workspace.name
  );
  const organizationSwitcher = useSwitcherData(
    () => getOrganizationsForSwitcherAction(),
    t("common.failed_to_load_organizations"),
    undefined,
    organization.name
  );
  const { load: loadWorkspaces } = workspaceSwitcher;
  const { load: loadOrganizations } = organizationSwitcher;
  const [openCreateWorkspaceModal, setOpenCreateWorkspaceModal] = useState(false);
  const [openWorkspaceLimitModal, setOpenWorkspaceLimitModal] = useState(false);

  useEffect(() => {
    // The hook guards against duplicate/looping loads internally.
    if (isWorkspaceDropdownOpen) {
      void loadWorkspaces();
    }
  }, [isWorkspaceDropdownOpen, loadWorkspaces]);

  useEffect(() => {
    if (isOrganizationDropdownOpen) {
      void loadOrganizations();
    }
  }, [isOrganizationDropdownOpen, loadOrganizations]);

  const getMainNavigationLink = () => {
    if (isBilling) return getBillingFallbackPath(organization.id, isFormbricksCloud);
    return getWorkspaceHomePath(membershipRole, workspace.id);
  };
  const mainNavigationLink = getMainNavigationLink();

  const handleWorkspaceChange = (workspaceId: string) => {
    const targetPath = getWorkspaceHomePath(membershipRole, workspaceId);
    startTransition(() => {
      setIsWorkspaceDropdownOpen(false);
      router.push(targetPath);
    });
  };

  const handleOrganizationChange = (organizationId: string) => {
    const targetPath = getOrganizationSwitchPath({
      organizationId,
      currentOrganizationId: organization.id,
      membershipRole,
    });
    startTransition(() => {
      setIsOrganizationDropdownOpen(false);
      router.push(targetPath);
    });
  };

  const handleWorkspaceCreate = () => {
    if (!workspaceSwitcher.hasLoaded || workspaceSwitcher.isLoading) {
      return;
    }

    if (workspaceSwitcher.items.length >= organizationWorkspacesLimit) {
      setOpenWorkspaceLimitModal(true);
      return;
    }

    setOpenCreateWorkspaceModal(true);
  };

  const workspaceLimitModalButtons = (): [ModalButton, ModalButton] => {
    if (isFormbricksCloud) {
      return [
        {
          text: t("workspace.settings.billing.upgrade"),
          href: `/organizations/${organization.id}/settings/billing`,
        },
        {
          text: t("common.cancel"),
          onClick: () => setOpenWorkspaceLimitModal(false),
        },
      ];
    }

    return [
      {
        text: t("workspace.settings.billing.upgrade"),
        href: isLicenseActive
          ? `/organizations/${organization.id}/settings/enterprise`
          : "https://formbricks.com/upgrade-self-hosted-license?utm_source=formbricks-app&utm_medium=webapp&utm_campaign=upgrade_prompt_nav",
      },
      {
        text: t("common.cancel"),
        onClick: () => setOpenWorkspaceLimitModal(false),
      },
    ];
  };

  const handleSettingsWorkspaceChange = useCallback(
    (id: string) => {
      startTransition(() => {
        router.push(`/workspaces/${id}/settings/workspace/general`);
      });
    },
    [router]
  );

  const handleSettingsOrganizationChange = useCallback(
    (id: string) => {
      startTransition(() => {
        router.push(
          getOrganizationSwitchPath({
            organizationId: id,
            currentOrganizationId: organization.id,
            membershipRole,
          })
        );
      });
    },
    [router, organization.id, membershipRole]
  );

  const switcherTriggerClasses = cn(
    "w-full border-t px-3 py-3 text-left transition-colors duration-200 hover:bg-slate-50 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-slate-500 focus-visible:ring-inset",
    isCollapsed ? "flex items-center justify-center" : ""
  );

  const switcherIconClasses =
    "flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-slate-100 text-slate-600";
  const mainNavIconClassName = "h-4 w-4 shrink-0";
  const isInitialWorkspacesLoading =
    isWorkspaceDropdownOpen && !workspaceSwitcher.hasLoaded && !workspaceSwitcher.error;

  return (
    <>
      {workspace && (
        <aside
          className={cn(
            "z-40 flex flex-col justify-between rounded-r-xl border-r border-slate-200 bg-white pt-3 shadow-md transition-all duration-100",
            isSettingsMode || !isCollapsed ? "w-sidebar-collapsed" : "w-sidebar-expanded"
          )}>
          {isSettingsMode ? (
            <div className="flex flex-col overflow-hidden">
              <div className="mb-2 px-3">
                <GoBackButton url={`/workspaces/${workspace.id}/surveys`} />
              </div>

              {/* Settings sidebar content */}
              <SettingsSidebarContent
                workspaceId={workspace.id}
                workspaceName={workspace.name}
                organizationId={organization.id}
                organizationName={organization.name}
                membershipRole={membershipRole}
                isFormbricksCloud={isFormbricksCloud}
                isCollapsed={false}
                isTextVisible={false}
                workspaces={workspaceSwitcher.items}
                isLoadingWorkspaces={workspaceSwitcher.isLoading}
                onWorkspaceChange={handleSettingsWorkspaceChange}
                onWorkspaceDropdownOpen={() =>
                  workspaceSwitcher.error ? workspaceSwitcher.retry() : workspaceSwitcher.load()
                }
                errorWorkspaces={workspaceSwitcher.error}
                onWorkspaceRetry={workspaceSwitcher.retry}
                organizations={organizationSwitcher.items}
                isLoadingOrganizations={organizationSwitcher.isLoading}
                onOrganizationChange={handleSettingsOrganizationChange}
                onOrganizationDropdownOpen={() =>
                  organizationSwitcher.error ? organizationSwitcher.retry() : organizationSwitcher.load()
                }
                errorOrganizations={organizationSwitcher.error}
                onOrganizationRetry={organizationSwitcher.retry}
              />
            </div>
          ) : (
            <div>
              {/* Logo and Toggle */}

              <MainNavigationHeader
                isCollapsed={isCollapsed}
                isTextVisible={isTextVisible}
                homeHref={mainNavigationLink}
                onToggle={toggleSidebar}
              />

              {/* Main Nav */}
              <ul className="space-y-2">
                {visibleNavigationSections.map((section) => (
                  <li key={section.id}>
                    {!isCollapsed && !isTextVisible && (
                      <p className="px-4 pt-2 pb-1 text-xs font-semibold tracking-wide text-slate-400 uppercase">
                        {section.name}
                      </p>
                    )}

                    <ul>
                      {section.items.map(
                        (item) =>
                          !item.isHidden && (
                            <NavigationLink
                              key={item.name}
                              href={item.href}
                              isActive={item.isActive}
                              isCollapsed={isCollapsed}
                              isTextVisible={isTextVisible}
                              disabled={item.disabled}
                              disabledMessage={item.disabled ? disabledNavigationMessage : undefined}
                              linkText={item.name}>
                              <item.icon className={mainNavIconClassName} strokeWidth={1.5} />
                            </NavigationLink>
                          )
                      )}
                    </ul>
                  </li>
                ))}

                {/* No settings for a Dashboard viewer; Profile and Notifications stay in the user menu. */}
                {!isDashboardViewer && (
                  <li className={cn("mt-2 border-t border-slate-100 pt-2", isCollapsed && "border-t-0 pt-0")}>
                    <ul>
                      <NavigationLink
                        href={settingsNavigationItem.href}
                        isActive={settingsNavigationItem.isActive}
                        isCollapsed={isCollapsed}
                        isTextVisible={isTextVisible}
                        disabled={settingsNavigationItem.disabled}
                        disabledMessage={
                          settingsNavigationItem.disabled ? disabledNavigationMessage : undefined
                        }
                        linkText={settingsNavigationItem.name}>
                        <settingsNavigationItem.icon className={mainNavIconClassName} strokeWidth={1.5} />
                      </NavigationLink>
                    </ul>
                  </li>
                )}
              </ul>
            </div>
          )}

          <div>
            {!isSettingsMode && (
              <MainNavigationNotices
                isCollapsed={isCollapsed}
                isOwnerOrManager={isOwnerOrManager}
                isFormbricksCloud={isFormbricksCloud}
                isDevelopment={isDevelopment}
                latestVersion={latestVersion}
                trialDaysRemaining={trialDaysRemaining}
                organization={organization}
                responseCount={responseCount}
              />
            )}

            <div className="flex flex-col">
              {!isSettingsMode && (
                <>
                  <DropdownMenu onOpenChange={setIsWorkspaceDropdownOpen}>
                    <DropdownMenuTrigger
                      asChild
                      id="workspaceDropdownTrigger"
                      className={switcherTriggerClasses}>
                      <button
                        type="button"
                        aria-label={isCollapsed ? t("common.choose_workspace") : undefined}
                        className={cn("flex w-full items-center gap-3", isCollapsed && "justify-center")}>
                        <span className={switcherIconClasses}>
                          <FoldersIcon className="size-4" strokeWidth={1.5} />
                        </span>
                        <SwitcherTriggerLabel
                          isCollapsed={isCollapsed}
                          isTextVisible={isTextVisible}
                          isPending={isPending}
                          name={workspace.name}
                          caption={t("common.workspace")}
                        />
                      </button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent
                      side="right"
                      sideOffset={10}
                      alignOffset={5}
                      align="end"
                      className={SWITCHER_DROPDOWN_CONTENT_CLASS_NAME}>
                      <SwitcherDropdownBody
                        type="workspace"
                        isLoading={workspaceSwitcher.isLoading || isInitialWorkspacesLoading}
                        error={workspaceSwitcher.error}
                        onRetry={workspaceSwitcher.retry}
                        items={workspaceSwitcher.items}
                        selectedId={workspace.id}
                        onSelect={handleWorkspaceChange}>
                        {isOwnerOrManager && (
                          <DropdownMenuCheckboxItem
                            onClick={handleWorkspaceCreate}
                            className="w-full cursor-pointer justify-between">
                            <span>{t("common.add_new_workspace")}</span>
                            <PlusIcon className="ml-2 size-4" strokeWidth={1.5} />
                          </DropdownMenuCheckboxItem>
                        )}
                      </SwitcherDropdownBody>
                    </DropdownMenuContent>
                  </DropdownMenu>

                  <DropdownMenu onOpenChange={setIsOrganizationDropdownOpen}>
                    <DropdownMenuTrigger
                      asChild
                      id="organizationDropdownTriggerSidebar"
                      className={switcherTriggerClasses}>
                      <button
                        type="button"
                        aria-label={isCollapsed ? t("common.choose_organization") : undefined}
                        className={cn("flex w-full items-center gap-3", isCollapsed && "justify-center")}>
                        <span className={switcherIconClasses}>
                          <Building2Icon className="size-4" strokeWidth={1.5} />
                        </span>
                        <SwitcherTriggerLabel
                          isCollapsed={isCollapsed}
                          isTextVisible={isTextVisible}
                          isPending={isPending}
                          name={organization.name}
                          caption={t("common.organization")}
                        />
                      </button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent
                      side="right"
                      sideOffset={10}
                      alignOffset={5}
                      align="end"
                      className={SWITCHER_DROPDOWN_CONTENT_CLASS_NAME}>
                      <SwitcherDropdownBody
                        type="organization"
                        isLoading={organizationSwitcher.isLoading}
                        error={organizationSwitcher.error}
                        onRetry={organizationSwitcher.retry}
                        items={organizationSwitcher.items}
                        selectedId={organization.id}
                        onSelect={handleOrganizationChange}
                      />
                    </DropdownMenuContent>
                  </DropdownMenu>
                </>
              )}

              <UserDropdown
                user={user}
                organizationId={organization.id}
                isCollapsed={isCollapsed}
                isTextVisible={isTextVisible}
                className="rounded-br-xl"
                isFormbricksSurveysConfigured={isFormbricksSurveysConfigured}
              />
            </div>
          </div>
        </aside>
      )}
      {openWorkspaceLimitModal && (
        <WorkspaceLimitModal
          open={openWorkspaceLimitModal}
          setOpen={setOpenWorkspaceLimitModal}
          buttons={workspaceLimitModalButtons()}
          workspaceLimit={organizationWorkspacesLimit}
          showLiteLicenseTip={!isFormbricksCloud && isNoLicense}
        />
      )}
      {openCreateWorkspaceModal && (
        <CreateWorkspaceModal
          open={openCreateWorkspaceModal}
          setOpen={setOpenCreateWorkspaceModal}
          organizationId={organization.id}
          isAccessControlAllowed={isAccessControlAllowed}
        />
      )}
    </>
  );
};
