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

import { useState, useEffect } from "react";
import { observer } from "mobx-react";
import { useRouter } from "next/navigation";
// pi dash package imports
import { EUserPermissions, EUserPermissionsLevel } from "@pi-dash/constants";
import { useTranslation } from "@pi-dash/i18n";
import { EmptyStateDetailed } from "@pi-dash/propel/empty-state";
import { Tabs } from "@pi-dash/propel/tabs";
// components
import { cn } from "@pi-dash/utils";
import AnalyticsFilterActions from "@/components/analytics/analytics-filter-actions";
import { PageHead } from "@/components/core/page-title";
// hooks
import { useCommandPalette } from "@/hooks/store/use-command-palette";
import { useProject } from "@/hooks/store/use-project";
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUserPermissions } from "@/hooks/store/user";
import { useAnalyticsTabs } from "@/pi-dash-web/components/analytics/use-analytics-tabs";
import type { Route } from "./+types/page";

function AnalyticsPage({ params }: Route.ComponentProps) {
  const { tabId } = params;

  // hooks
  const router = useRouter();

  // pi dash imports
  const { t } = useTranslation();

  // store hooks
  const { toggleCreateProjectModal } = useCommandPalette();
  const { workspaceProjectIds, loader } = useProject();
  const { currentWorkspace } = useWorkspace();
  const { allowPermissions } = useUserPermissions();

  const pageTitle = currentWorkspace?.name
    ? t("{workspace} - Analytics", { workspace: currentWorkspace?.name })
    : undefined;

  // permissions
  const canPerformEmptyStateActions = allowPermissions(
    [EUserPermissions.ADMIN, EUserPermissions.MEMBER],
    EUserPermissionsLevel.WORKSPACE
  );

  const workspaceSlug = params.workspaceSlug;
  const ANALYTICS_TABS = useAnalyticsTabs(workspaceSlug.toString());

  const [selectedTab, setSelectedTab] = useState(tabId || ANALYTICS_TABS[0]?.key);

  useEffect(() => {
    if (tabId) {
      setSelectedTab(tabId);
    }
  }, [tabId]);

  // Handle tab change
  const handleTabChange = (value: string) => {
    setSelectedTab(value);
    router.push(`/${currentWorkspace?.slug}/analytics/${value}`);
  };

  return (
    <>
      <PageHead title={pageTitle} />
      {workspaceProjectIds && (
        <>
          {workspaceProjectIds.length > 0 || loader === "init-loader" ? (
            <div className="flex h-full overflow-hidden">
              <Tabs value={selectedTab} onValueChange={handleTabChange} className="h-full w-full">
                <div className={"flex h-full w-full flex-col"}>
                  <div
                    className={cn(
                      "flex w-full items-center justify-between gap-4 overflow-hidden border-b border-subtle bg-surface-1 px-6 py-2"
                    )}
                  >
                    <Tabs.List className={"flex h-7 w-fit overflow-x-auto"}>
                      {ANALYTICS_TABS.map((tab) => (
                        <Tabs.Trigger
                          key={tab.key}
                          value={tab.key}
                          disabled={tab.isDisabled}
                          size="md"
                          className="h-6 px-3"
                          onClick={() => {
                            if (!tab.isDisabled) {
                              handleTabChange(tab.key);
                            }
                          }}
                        >
                          {tab.label}
                        </Tabs.Trigger>
                      ))}
                    </Tabs.List>

                    <div className="flex-shrink-0">
                      <AnalyticsFilterActions />
                    </div>
                  </div>
                  {ANALYTICS_TABS.map((tab) => (
                    <Tabs.Content
                      key={tab.key}
                      value={tab.key}
                      className={"h-full overflow-hidden overflow-y-auto px-2"}
                    >
                      <tab.content />
                    </Tabs.Content>
                  ))}
                </div>
              </Tabs>
            </div>
          ) : (
            <EmptyStateDetailed
              assetKey="project"
              title={t("No project")}
              description={t("To create work items or manage your work, you need to create a project or be a part of one.")}
              actions={[
                {
                  label: "Create a project",
                  onClick: () => {
                    toggleCreateProjectModal(true);
                  },
                  disabled: !canPerformEmptyStateActions,
                },
              ]}
            />
          )}
        </>
      )}
    </>
  );
}

export default observer(AnalyticsPage);
