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

import { useCallback, useEffect, useRef, useState } from "react";
import { observer } from "mobx-react";
import { useTranslation } from "@plane/i18n";
// plane imports
import { Loader } from "@plane/ui";
// components
import { InboxSidebarLoader } from "@/components/ui/loader/layouts/project-inbox/inbox-sidebar-loader";
// hooks
import { useProject } from "@/hooks/store/use-project";
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { useAppRouter } from "@/hooks/use-app-router";
import { useIntersectionObserver } from "@/hooks/use-intersection-observer";
// local imports
import { InboxEmptyState } from "../empty-state";
import { InboxIssueList } from "./inbox-list";

type IInboxSidebarProps = {
  workspaceSlug: string;
  projectId: string;
  inboxIssueId: string | undefined;
  setIsMobileSidebar: (value: boolean) => void;
};

export const InboxSidebar = observer(function InboxSidebar(props: IInboxSidebarProps) {
  const { workspaceSlug, projectId, inboxIssueId, setIsMobileSidebar } = props;
  // router
  const router = useAppRouter();
  // ref
  const containerRef = useRef<HTMLDivElement>(null);
  const [elementRef, setElementRef] = useState<HTMLDivElement | null>(null);
  // plane hooks
  const { t } = useTranslation();
  // store
  const { currentProjectDetails } = useProject();
  const {
    loader,
    filteredInboxIssueIds,
    inboxIssuePaginationInfo,
    fetchInboxPaginationIssues,
    getAppliedFiltersCount,
  } = useProjectInbox();
  // derived values
  const fetchNextPages = useCallback(() => {
    if (!workspaceSlug || !projectId) return;
    fetchInboxPaginationIssues(workspaceSlug.toString(), projectId.toString());
  }, [workspaceSlug, projectId, fetchInboxPaginationIssues]);

  // page observer
  useIntersectionObserver(containerRef, elementRef, fetchNextPages, "20%");

  useEffect(() => {
    if (!workspaceSlug || !projectId || inboxIssueId !== undefined || filteredInboxIssueIds.length === 0) return;

    router.push(`/${workspaceSlug}/projects/${projectId}/intake?inboxIssueId=${filteredInboxIssueIds[0]}`);
  }, [filteredInboxIssueIds, inboxIssueId, projectId, router, workspaceSlug]);

  return (
    <div className="h-full w-full flex-shrink-0 rounded-[28px] border border-subtle/70 bg-surface-1/75 shadow-[0px_8px_24px_rgba(0,0,0,0.14)] backdrop-blur-2xl">
      <div className="relative flex h-full w-full flex-col overflow-hidden">
        {loader != undefined && loader === "filter-loading" && !inboxIssuePaginationInfo?.next_page_results ? (
          <InboxSidebarLoader />
        ) : (
          <div className="vertical-scrollbar scrollbar-md h-full w-full overflow-hidden overflow-y-auto p-3" ref={containerRef}>
            {filteredInboxIssueIds.length > 0 ? (
              <div className="space-y-2 pb-1">
                <InboxIssueList
                  setIsMobileSidebar={setIsMobileSidebar}
                  workspaceSlug={workspaceSlug}
                  projectId={projectId}
                  projectIdentifier={currentProjectDetails?.identifier}
                  inboxIssueIds={filteredInboxIssueIds}
                />
              </div>
            ) : (
              <div className="flex h-full w-full items-center justify-center">
                {getAppliedFiltersCount > 0 ? (
                  <InboxEmptyState
                    compact
                    title={t("common_empty_state.search.title")}
                    description={t("common_empty_state.search.description")}
                  />
                ) : (
                  <InboxEmptyState
                    compact
                    title={t("project_empty_state.intake_sidebar.title")}
                    description={t("project_empty_state.intake_sidebar.description")}
                  />
                )}
              </div>
            )}
            <div ref={setElementRef}>
              {inboxIssuePaginationInfo?.next_page_results && (
                <Loader className="mx-auto w-full space-y-4 px-2 py-4">
                  <Loader.Item height="64px" width="w-100" />
                  <Loader.Item height="64px" width="w-100" />
                </Loader>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
});
