"use client";

import { useSetAtom } from "jotai";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { getTriggerSurveyId } from "@formbricks/workflows";
import { WorkflowCanvas } from "@/modules/ee/workflows/components/canvas/workflow-canvas";
import { WorkflowInspectorPanel } from "@/modules/ee/workflows/components/inspector/workflow-inspector-panel";
import { WorkflowEmailAuthoringProvider } from "@/modules/ee/workflows/components/workflow-email-authoring-context";
import { useReconcileTriggerEndingCards } from "@/modules/ee/workflows/hooks/use-reconcile-trigger-ending-cards";
import { useTrackWorkflowSurface } from "@/modules/ee/workflows/hooks/use-track-workflow-surface";
import { useWorkflowSurveyOptions } from "@/modules/ee/workflows/hooks/use-trigger-survey-picker";
import { useWorkflowBuilder } from "@/modules/ee/workflows/hooks/use-workflow-builder";
import { useWorkflowNodeUrlSync } from "@/modules/ee/workflows/hooks/use-workflow-node-url-sync";
import { resolveBoundTriggerSurvey } from "@/modules/ee/workflows/lib/bound-survey";
import { WorkflowBuilderBodyLoading } from "@/modules/ee/workflows/loading";
import {
  hasBoundTriggerSurveyAtom,
  isSurveyVisibilityEnabledAtom,
  isTriggerSurveyRestrictedAtom,
} from "@/modules/ee/workflows/state/editor";
import type { TWorkflowEmailAuthoringContext } from "@/modules/ee/workflows/types/email-authoring-context";
import { isRestrictedSurveyPick } from "@/modules/survey/visibility/lib/outbound";

interface WorkflowBuilderPageProps {
  workspaceId: string;
  workflowId: string;
  isReadOnly: boolean;
  emailAuthoringContext: TWorkflowEmailAuthoringContext;
  /** ENG-3395: the restricted-surveys gate. */
  surveyVisibilityEnabled: boolean;
}

export const WorkflowBuilderPage = ({
  workspaceId,
  workflowId,
  isReadOnly,
  emailAuthoringContext,
  surveyVisibilityEnabled,
}: Readonly<WorkflowBuilderPageProps>) => {
  const { t } = useTranslation();
  const builder = useWorkflowBuilder({ workspaceId, workflowId, isReadOnly });
  const setHasBoundTriggerSurvey = useSetAtom(hasBoundTriggerSurveyAtom);
  const setIsTriggerSurveyRestricted = useSetAtom(isTriggerSurveyRestrictedAtom);
  const setIsSurveyVisibilityEnabled = useSetAtom(isSurveyVisibilityEnabledAtom);
  const surveyOptionsQuery = useWorkflowSurveyOptions(workspaceId);

  // This page owns pushing the "does the trigger's survey resolve" fact into the shared atom the
  // validity + canvas checks read. Two sources, so the flag flips the moment a survey is picked:
  // the server-resolved authoring context (authoritative — catches deleted surveys) still lags a
  // save + refresh behind the draft, so membership in the workspace survey list (the same query
  // the trigger's picker offers choices from) vouches for a just-picked id immediately.
  // Keyed on the inputs (not the computed boolean): hydration resets the atom to its optimistic
  // default, and a boolean-keyed effect would skip re-syncing when the computed value happens to
  // match its pre-hydration result.
  const definition = builder.definition;
  const surveyOptions = surveyOptionsQuery.options;
  useEffect(() => {
    const triggerSurveyId = getTriggerSurveyId(definition?.trigger);
    const isBound =
      Boolean(resolveBoundTriggerSurvey(emailAuthoringContext, definition)) ||
      (triggerSurveyId !== null && surveyOptions.some((option) => option.id === triggerSurveyId));
    setHasBoundTriggerSurvey(isBound);
  }, [emailAuthoringContext, definition, surveyOptions, setHasBoundTriggerSurvey]);

  // ENG-3395: a restricted trigger survey is refused by enable and test and skipped by the runner, so
  // the editor reports it as a problem up front. Same keying as above, for the same reason.
  useEffect(() => {
    const triggerSurveyId = getTriggerSurveyId(definition?.trigger);
    const triggerSurvey = surveyOptions.find((option) => option.id === triggerSurveyId);
    setIsSurveyVisibilityEnabled(surveyVisibilityEnabled);
    setIsTriggerSurveyRestricted(
      triggerSurvey ? isRestrictedSurveyPick(surveyVisibilityEnabled, triggerSurvey) : false
    );
  }, [
    definition,
    surveyOptions,
    surveyVisibilityEnabled,
    setIsSurveyVisibilityEnabled,
    setIsTriggerSurveyRestricted,
  ]);

  // Prune trigger ending-card ids whose endings were deleted. On the page (not the trigger form) so
  // the canvas summary and enable gate stay correct without opening the inspector.
  useReconcileTriggerEndingCards({ definition, isEditable: builder.canEditDefinition });

  // Deep-link the inspected node (?node=…) once the editor is hydrated.
  useWorkflowNodeUrlSync({ isEnabled: Boolean(builder.workflow) });

  // Analytics: the builder counts as visited once the workflow is loaded, not while the skeleton shows.
  useTrackWorkflowSurface(builder.workflow ? "builder" : null, {
    workflowId,
    workflowStatus: builder.workflow?.status,
    isReadOnly,
  });

  if (builder.isLoading) {
    return <WorkflowBuilderBodyLoading />;
  }

  if (!builder.workflow) {
    return (
      <div className="rounded-lg border border-slate-200 bg-white p-6 text-sm text-slate-600">
        {builder.loadError ?? t("workspace.workflows.load_failed")}
      </div>
    );
  }

  return (
    // Claims the height the page layout hands down (`min-h-0` so it may shrink below its content
    // rather than push the page taller), and both columns stretch to fill it.
    <div className="flex min-h-0 flex-1 flex-col gap-4">
      <WorkflowEmailAuthoringProvider value={emailAuthoringContext}>
        {/* Canvas and inspector share one height, derived from this row rather than computed from
            the viewport. Each owns its own overflow: the canvas clips (it pans), the inspector
            scrolls — so however long a config form runs, the page itself never grows. */}
        <section className="flex min-h-0 flex-1 gap-4">
          <WorkflowCanvas isEditable={builder.canEditDefinition} />
          <WorkflowInspectorPanel isEditingNode={builder.canEditDefinition} />
        </section>
      </WorkflowEmailAuthoringProvider>
    </div>
  );
};
