/**
 * Copyright (c) 2023-present Pi Dash Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import { observer } from "mobx-react";
import { useParams, usePathname } from "next/navigation";
import { useTheme } from "next-themes";
// pi dash imports
import { useTranslation } from "@pi-dash/i18n";
import type { THomeWidgetKeys, THomeWidgetProps } from "@pi-dash/types";
// assets
import darkWidgetsAsset from "@/app/assets/empty-state/dashboard/widgets-dark.webp?url";
import lightWidgetsAsset from "@/app/assets/empty-state/dashboard/widgets-light.webp?url";
// components
import { SimpleEmptyState } from "@/components/empty-state/simple-empty-state-root";
// hooks
import { useHome } from "@/hooks/store/use-home";
import { useProject } from "@/hooks/store/use-project";
// pi dash web components
import { HomePageHeader } from "@/pi-dash-web/components/home/header";
// local imports
import { HomeLoader, NoProjectsEmptyState, RecentActivityWidget } from "./widgets";
import { DashboardQuickLinks } from "./widgets/links";
import { ManageWidgetsModal } from "./widgets/manage";

export const HOME_WIDGETS_LIST: {
  [key in THomeWidgetKeys]: {
    component: React.FC<THomeWidgetProps> | null;
    fullWidth: boolean;
    title: string;
  };
} = {
  quick_links: {
    component: DashboardQuickLinks,
    fullWidth: false,
    title: "Quicklinks",
  },
  recents: {
    component: RecentActivityWidget,
    fullWidth: false,
    title: "Recents",
  },
  my_stickies: {
    component: null,
    fullWidth: false,
    title: "Your stickies",
  },
  new_at_pi_dash: {
    component: null,
    fullWidth: false,
    title: "New at Pi Dash",
  },
  quick_tutorial: {
    component: null,
    fullWidth: false,
    title: "Quick tutorial",
  },
};

// Widgets hidden from users. `my_stickies` is part of the inherited Stickies
// feature, which Pi Dash does not surface (PDASHOSS01-7). Its dashboard
// component is already `null`, but the Manage Widgets modal still enumerates
// every server-provided widget key — so it must be filtered there too.
export const HIDDEN_HOME_WIDGET_KEYS: ReadonlySet<THomeWidgetKeys> = new Set(["my_stickies"]);

export const DashboardWidgets = observer(function DashboardWidgets() {
  // router
  const { workspaceSlug } = useParams();
  // navigation
  const pathname = usePathname();
  // theme hook
  const { resolvedTheme } = useTheme();
  // store hooks
  const { toggleWidgetSettings, widgetsMap, showWidgetSettings, orderedWidgets, loading } = useHome();
  const { loader } = useProject();
  // pi dash hooks
  const { t } = useTranslation();
  // derived values
  const noWidgetsResolvedPath = resolvedTheme === "light" ? lightWidgetsAsset : darkWidgetsAsset;
  // Only consider widgets that are actually surfaced to users when deciding
  // between the dashboard and the empty state. `my_stickies` is hidden
  // (PDASHOSS01-7) and renders nothing, so an enabled-but-hidden stickies
  // widget must not suppress the "all widgets off" empty state.
  const visibleWidgets = orderedWidgets.filter((key) => !HIDDEN_HOME_WIDGET_KEYS.has(key));
  const isAnyVisibleWidgetEnabled = visibleWidgets.some((key) => widgetsMap[key]?.is_enabled);

  // derived values
  const isWikiApp = pathname.includes(`/${workspaceSlug.toString()}/pages`);
  if (!workspaceSlug) return null;
  if (loading || loader !== "loaded") return <HomeLoader />;

  return (
    <div className="relative flex h-full w-full flex-col gap-7">
      <HomePageHeader />
      <ManageWidgetsModal
        workspaceSlug={workspaceSlug.toString()}
        isModalOpen={showWidgetSettings}
        handleOnClose={() => toggleWidgetSettings(false)}
      />
      {!isWikiApp && <NoProjectsEmptyState />}

      {isAnyVisibleWidgetEnabled ? (
        <div className="flex flex-col">
          {visibleWidgets.map((key) => {
            const WidgetComponent = HOME_WIDGETS_LIST[key]?.component;
            const isEnabled = widgetsMap[key]?.is_enabled;
            if (!WidgetComponent || !isEnabled) return null;
            return (
              <div key={key} className="py-4">
                <WidgetComponent workspaceSlug={workspaceSlug.toString()} />
              </div>
            );
          })}
        </div>
      ) : (
        <div className="grid h-full w-full place-items-center">
          <SimpleEmptyState
            title={t("It's Quiet Without Widgets, Turn Them On")}
            description={t(
              "It looks like all your widgets are turned off. Enable them\nnow to enhance your experience!"
            )}
            assetPath={noWidgetsResolvedPath}
          />
        </div>
      )}
    </div>
  );
});
