import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { type Dispatch, type SetStateAction, useMemo } from "react";
import { TI18nString } from "@formbricks/types/i18n";
import { TSurveyElement } from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import { type TWorkspaceWithoutCustomCss } from "@/modules/custom-css/lib/types";
import { BlockCard } from "@/modules/survey/editor/components/block-card";

interface BlocksDroppableProps {
  localSurvey: TSurvey;
  persistedSurvey: TSurvey;
  setLocalSurvey: Dispatch<SetStateAction<TSurvey>>;
  workspace: TWorkspaceWithoutCustomCss;
  moveElement: (elementIdx: number, up: boolean) => void;
  updateElement: (elementIdx: number, updatedAttributes: Record<string, unknown>) => void;
  updateBlockName: (blockIdx: number, name: string) => void;
  updateBlockButtonLabel: (
    blockIndex: number,
    labelKey: "buttonLabel" | "backButtonLabel",
    labelValue: TI18nString | undefined
  ) => void;
  deleteElement: (elementIdx: number) => void;
  duplicateElement: (elementIdx: number) => void;
  activeElementId: string | null;
  setActiveElementId: (elementId: string | null) => void;
  invalidElements: string[] | null;
  addElement: (element: TSurveyElement, index?: number) => void;
  isFormbricksCloud: boolean;
  isCxMode: boolean;
  locale: TUserLocale;
  isStorageConfigured: boolean;
  isExternalUrlsAllowed: boolean;
  duplicateBlock: (blockId: string) => void;
  deleteBlock: (blockId: string) => void;
  moveBlock: (blockId: string, direction: "up" | "down") => void;
  addElementToBlock: (element: TSurveyElement, blockId: string, afterElementIdx: number) => void;
  moveElementToBlock?: (elementId: string, targetBlockId: string) => void;
  // Id of the block the user last pressed or focused; that card re-renders on every survey change.
  lastInteractedBlockId: string | null;
  onBlockInteract: (blockId: string) => void;
}

export const BlocksDroppable = ({
  activeElementId,
  deleteElement,
  duplicateElement,
  invalidElements,
  localSurvey,
  persistedSurvey,
  setLocalSurvey,
  moveElement,
  workspace,
  setActiveElementId,
  updateElement,
  updateBlockName,
  updateBlockButtonLabel,
  addElement,
  isFormbricksCloud,
  isCxMode,
  locale,
  isStorageConfigured = true,
  isExternalUrlsAllowed,
  duplicateBlock,
  deleteBlock,
  moveBlock,
  addElementToBlock,
  moveElementToBlock,
  lastInteractedBlockId,
  onBlockInteract,
}: Readonly<BlocksDroppableProps>) => {
  const [parent] = useAutoAnimate();

  // SortableContext memoizes its context value on `items`. Handing it `localSurvey.blocks` (a new
  // array on every edit) would re-render every useSortable consumer — each memoized BlockCard — on
  // every keystroke, so give it an id list that only changes when the block ids or their order do.
  const blockIdsKey = JSON.stringify(localSurvey.blocks.map((block) => block.id));
  const blockIds = useMemo(() => JSON.parse(blockIdsKey) as string[], [blockIdsKey]);

  return (
    <div className="group mb-5 flex w-full flex-col gap-5" ref={parent}>
      <SortableContext items={blockIds} strategy={verticalListSortingStrategy}>
        {localSurvey.blocks.map((block, blockIdx) => {
          // Check if this is the last block and has elements
          const isLastBlock = blockIdx === localSurvey.blocks.length - 1;
          const lastElementIndex = block.elements.length - 1;

          return (
            <BlockCard
              key={block.id}
              localSurvey={localSurvey}
              persistedSurvey={persistedSurvey}
              setLocalSurvey={setLocalSurvey}
              workspace={workspace}
              block={block}
              blockIdx={blockIdx}
              moveElement={moveElement}
              updateElement={updateElement}
              updateBlockName={updateBlockName}
              updateBlockButtonLabel={updateBlockButtonLabel}
              duplicateElement={duplicateElement}
              deleteElement={deleteElement}
              activeElementId={activeElementId}
              setActiveElementId={setActiveElementId}
              lastElement={isLastBlock}
              lastElementIndex={lastElementIndex}
              invalidElements={invalidElements ?? undefined}
              addElement={addElement}
              isFormbricksCloud={isFormbricksCloud}
              isCxMode={isCxMode}
              locale={locale}
              isStorageConfigured={isStorageConfigured}
              isExternalUrlsAllowed={isExternalUrlsAllowed}
              duplicateBlock={duplicateBlock}
              deleteBlock={deleteBlock}
              moveBlock={moveBlock}
              addElementToBlock={addElementToBlock}
              moveElementToBlock={moveElementToBlock}
              totalBlocks={localSurvey.blocks.length}
              isLastInteracted={lastInteractedBlockId === block.id}
              onInteract={onBlockInteract}
            />
          );
        })}
      </SortableContext>
    </div>
  );
};
