/**
 * 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, useMemo, useRef } from "react";
import { observer } from "mobx-react";
// plane imports
import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import { useTranslation } from "@plane/i18n";
import { EOnboardingSteps } from "@plane/types";
// hooks
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUser, useUserProfile } from "@/hooks/store/user";
// local components
import { OnboardingHeader } from "./header";
import { OnboardingStepRoot } from "./steps";

const buildWorkspaceSlug = (email?: string, userId?: string) => {
  const emailPrefix = email?.split("@")[0]?.toLowerCase() ?? "";
  const normalized = emailPrefix
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 24);
  const fallbackSeed = userId?.replace(/[^a-z0-9]+/gi, "").toLowerCase().slice(0, 12) || Date.now().toString(36);
  const base = normalized || `user-${fallbackSeed}`;

  return `${base}-${Date.now().toString(36)}`.slice(0, 48);
};

export const OnboardingRoot = observer(function OnboardingRoot() {
  const { t } = useTranslation();
  const completingRef = useRef(false);
  // store hooks
  const { data: user } = useUser();
  const { data: userProfile, finishUserOnboarding } = useUserProfile();
  const { workspaces, createWorkspace, fetchWorkspaces } = useWorkspace();

  const workspacesList = useMemo(() => Object.values(workspaces ?? {}), [workspaces]);

  const completeProfileOnboarding = useCallback(async () => {
    if (!user || completingRef.current) return;

    completingRef.current = true;

    try {
      let workspaceId = workspacesList[0]?.id;

      if (!workspaceId) {
        const workspaceResponse = await createWorkspace({
          name: user.display_name || user.first_name || user.email?.split("@")[0] || "NODE.DC",
          slug: buildWorkspaceSlug(user.email, user.id),
          organization_size: "Just myself",
        });

        workspaceId = workspaceResponse.id;
        await fetchWorkspaces();
      }

      await finishUserOnboarding(workspaceId);
    } catch (_error) {
      setToast({
        type: TOAST_TYPE.ERROR,
        title: t("error"),
        message: t("onboarding.profile.user_details_failed"),
      });
    } finally {
      completingRef.current = false;
    }
  }, [createWorkspace, fetchWorkspaces, finishUserOnboarding, t, user, workspacesList]);

  const handleStepChange = useCallback(
    async (step: EOnboardingSteps) => {
      if (step !== EOnboardingSteps.PROFILE_SETUP) return;
      await completeProfileOnboarding();
    },
    [completeProfileOnboarding]
  );

  useEffect(() => {
    if (!userProfile?.id || userProfile?.is_onboarded || !userProfile?.onboarding_step?.profile_complete) return;
    void completeProfileOnboarding();
  }, [completeProfileOnboarding, userProfile?.id, userProfile?.is_onboarded, userProfile?.onboarding_step?.profile_complete]);

  return (
    <div className="flex h-full flex-col">
      <OnboardingHeader />
      <OnboardingStepRoot handleStepChange={handleStepChange} />
    </div>
  );
});
