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

import { useEffect, useState } from "react";
import { observer } from "mobx-react";
import useSWR from "swr";
import { EUserPermissions, EUserPermissionsLevel } from "@plane/constants";
import type { TNameDescriptionLoader } from "@plane/types";
import { ContentWrapper } from "@plane/ui";
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { useUser, useUserPermissions } from "@/hooks/store/user";
import { useAppRouter } from "@/hooks/use-app-router";
import { ExternalContoursIssueActionsHeader } from "./issue-header";
import { ExternalContoursIssueMainContent } from "./issue-root";

type Props = {
  workspaceSlug: string;
  projectId: string;
  inboxIssueId: string;
  isMobileSidebar: boolean;
  setIsMobileSidebar: (value: boolean) => void;
};

export const ExternalContoursContentRoot = observer(function ExternalContoursContentRoot(props: Props) {
  const { workspaceSlug, projectId, inboxIssueId, isMobileSidebar, setIsMobileSidebar } = props;
  const router = useAppRouter();
  const [isSubmitting, setIsSubmitting] = useState<TNameDescriptionLoader>("saved");
  const { data: currentUser } = useUser();
  const { currentTab, fetchInboxIssueById, getIssueInboxByIssueId, getIsIssueAvailable } = useProjectInbox();
  const inboxIssue = getIssueInboxByIssueId(inboxIssueId);
  const { allowPermissions, getProjectRoleByWorkspaceSlugAndProjectId } = useUserPermissions();

  const isIssueAvailable = getIsIssueAvailable(inboxIssueId?.toString() || "");

  useEffect(() => {
    if (!isIssueAvailable && inboxIssueId) {
      router.replace(`/${workspaceSlug}/projects/${projectId}/external-contours?currentTab=${currentTab}`);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isIssueAvailable]);

  useSWR(
    workspaceSlug && projectId && inboxIssueId ? `PROJECT_EXTERNAL_CONTOUR_ISSUE_DETAIL_${workspaceSlug}_${projectId}_${inboxIssueId}` : null,
    workspaceSlug && projectId && inboxIssueId ? () => fetchInboxIssueById(workspaceSlug, projectId, inboxIssueId) : null,
    { revalidateOnFocus: false, revalidateIfStale: false }
  );

  const isEditable =
    allowPermissions([EUserPermissions.ADMIN], EUserPermissionsLevel.PROJECT, workspaceSlug, projectId) ||
    inboxIssue?.issue.created_by === currentUser?.id;

  const isGuest = getProjectRoleByWorkspaceSlugAndProjectId(workspaceSlug, projectId) === EUserPermissions.GUEST;
  const isOwner = inboxIssue?.issue.created_by === currentUser?.id;
  const readOnly = !isOwner && isGuest;

  if (!inboxIssue) return <></>;

  return (
    <div className="relative flex h-full w-full flex-col overflow-hidden">
      <div className="z-[11] min-h-[52px] flex-shrink-0">
        <ExternalContoursIssueActionsHeader
          setIsMobileSidebar={setIsMobileSidebar}
          isMobileSidebar={isMobileSidebar}
          workspaceSlug={workspaceSlug}
          projectId={projectId}
          inboxIssue={inboxIssue}
          isSubmitting={isSubmitting}
        />
      </div>
      <ContentWrapper className="divide-y-2 divide-subtle-1">
        <ExternalContoursIssueMainContent
          workspaceSlug={workspaceSlug}
          projectId={projectId}
          inboxIssue={inboxIssue}
          isEditable={isEditable && !readOnly}
          isSubmitting={isSubmitting}
          setIsSubmitting={setIsSubmitting}
        />
      </ContentWrapper>
    </div>
  );
});
