import { Suspense } from "react";
import { TOrganizationRole } from "@formbricks/types/memberships";
import { TOrganization } from "@formbricks/types/organizations";
import { SettingsCard } from "@/app/(app)/environments/[environmentId]/settings/components/SettingsCard";
import { INVITE_DISABLED, IS_FORMBRICKS_CLOUD, IS_STORAGE_CONFIGURED } from "@/lib/constants";
import { getTranslate } from "@/lingodotdev/server";
import { getIsMultiOrgEnabled } from "@/modules/ee/license-check/lib/utils";
import { getTeamsWhereUserIsAdmin } from "@/modules/ee/teams/lib/roles";
import { getTeamsByOrganizationId } from "@/modules/ee/teams/team-list/lib/team";
import { TOrganizationTeam } from "@/modules/ee/teams/team-list/types/team";
import { EditMemberships } from "@/modules/organization/settings/teams/components/edit-memberships";
import { OrganizationActions } from "@/modules/organization/settings/teams/components/edit-memberships/organization-actions";
import { getMembershipsByUserId } from "@/modules/organization/settings/teams/lib/membership";

interface MembersViewProps {
  membershipRole?: TOrganizationRole;
  organization: TOrganization;
  currentUserId: string;
  environmentId: string;
  isAccessControlAllowed: boolean;
  isUserManagementDisabledFromUi: boolean;
}

export const MembersLoading = () => (
  <div className="px-2">
    {Array.from(Array(2)).map((_, index) => (
      <div key={index} className="mt-4">
        <div className={`h-8 w-80 animate-pulse rounded-full bg-slate-200`} />
      </div>
    ))}
  </div>
);

export const MembersView = async ({
  membershipRole,
  organization,
  currentUserId,
  environmentId,
  isAccessControlAllowed,
  isUserManagementDisabledFromUi,
}: MembersViewProps) => {
  const t = await getTranslate();

  const userMemberships = await getMembershipsByUserId(currentUserId);
  const isLeaveOrganizationDisabled = userMemberships.length <= 1;

  const isMultiOrgEnabled = await getIsMultiOrgEnabled();

  // Fetch admin teams if they're a team admin
  const userAdminTeamIds = await getTeamsWhereUserIsAdmin(currentUserId, organization.id);
  const isTeamAdminUser = userAdminTeamIds.length > 0;

  let teams: TOrganizationTeam[] = [];

  if (isAccessControlAllowed) {
    teams = (await getTeamsByOrganizationId(organization.id)) ?? [];
  }

  return (
    <SettingsCard
      title={t("environments.settings.general.manage_members")}
      description={t("environments.settings.general.manage_members_description")}>
      {membershipRole && (
        <OrganizationActions
          organization={organization}
          membershipRole={membershipRole}
          role={membershipRole}
          isLeaveOrganizationDisabled={isLeaveOrganizationDisabled}
          isInviteDisabled={INVITE_DISABLED}
          isAccessControlAllowed={isAccessControlAllowed}
          isFormbricksCloud={IS_FORMBRICKS_CLOUD}
          isStorageConfigured={IS_STORAGE_CONFIGURED}
          environmentId={environmentId}
          isMultiOrgEnabled={isMultiOrgEnabled}
          teams={teams}
          isUserManagementDisabledFromUi={isUserManagementDisabledFromUi}
          isTeamAdmin={isTeamAdminUser}
          userAdminTeamIds={userAdminTeamIds}
        />
      )}

      {membershipRole && (
        <Suspense fallback={<MembersLoading />}>
          <EditMemberships
            isAccessControlAllowed={isAccessControlAllowed}
            organization={organization}
            currentUserId={currentUserId}
            role={membershipRole}
            isUserManagementDisabledFromUi={isUserManagementDisabledFromUi}
          />
        </Suspense>
      )}
    </SettingsCard>
  );
};
