"use client";

import { DndContext } from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { createId } from "@paralleldrive/cuid2";
import { PlusIcon } from "lucide-react";
import { type JSX, useEffect, useMemo, useRef, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { getLanguageLabel } from "@formbricks/i18n-utils/utils";
import {
  TSurveyElement,
  TSurveyElementChoice,
  TSurveyElementTypeEnum,
  TSurveyMultipleChoiceElement,
} from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import { createI18nString, extractLanguageCodes } from "@/lib/i18n/utils";
import { ElementFormInput } from "@/modules/survey/components/element-form-input";
import { BulkEditOptionsModal } from "@/modules/survey/editor/components/bulk-edit-options-modal";
import { ElementOptionChoice } from "@/modules/survey/editor/components/element-option-choice";
import { type TSetOptionHidden } from "@/modules/survey/editor/components/option-hide-button";
import {
  LOCK_TOOLTIP_DELAY_MS,
  PublishedLockNotice,
} from "@/modules/survey/editor/components/published-lock-notice";
import { NO_ELEMENT_LOCK, TElementLock } from "@/modules/survey/editor/lib/published-lock";
import {
  ensureSpecialChoicesOrder,
  getShuffleOptionAfterAddingSpecialChoice,
  getShuffleOptionAfterRemovingSpecialChoice,
} from "@/modules/survey/editor/lib/special-choices";
import { findOptionUse } from "@/modules/survey/editor/lib/utils";
import { Button } from "@/modules/ui/components/button";
import { Label } from "@/modules/ui/components/label";
import { TooltipRenderer } from "@/modules/ui/components/tooltip";

interface MultipleChoiceElementFormProps {
  readonly localSurvey: TSurvey;
  readonly element: TSurveyMultipleChoiceElement;
  readonly elementIdx: number;
  readonly updateElement: (elementIdx: number, updatedAttributes: Partial<TSurveyElement>) => void;
  readonly selectedLanguageCode: string;
  readonly isInvalid: boolean;
  readonly locale: TUserLocale;
  readonly isStorageConfigured: boolean;
  readonly isExternalUrlsAllowed?: boolean;
  readonly lock?: TElementLock;
  /** The Hide quick action on each option (ENG-6949). */
  readonly onSetOptionHidden?: TSetOptionHidden;
}

export const MultipleChoiceElementForm = ({
  element,
  elementIdx,
  updateElement,
  isInvalid,
  localSurvey,
  selectedLanguageCode,
  locale,
  isStorageConfigured = true,
  isExternalUrlsAllowed,
  lock = NO_ELEMENT_LOCK,
  onSetOptionHidden,
}: MultipleChoiceElementFormProps): JSX.Element => {
  const { t } = useTranslation();
  const lastChoiceRef = useRef<HTMLInputElement>(null);
  const [isNew, setIsNew] = useState(true);
  const [isInvalidValue, setisInvalidValue] = useState<string | null>(null);
  const [isBulkEditOpen, setIsBulkEditOpen] = useState(false);

  const elementRef = useRef<HTMLInputElement>(null);
  const surveyLanguageCodes = extractLanguageCodes(localSurvey.languages);
  const surveyLanguages = localSurvey.languages ?? [];

  const updateChoice = (choiceIdx: number, updatedAttributes: Partial<TSurveyElementChoice>) => {
    let newChoices: TSurveyElementChoice[] = [];
    if (element.choices) {
      newChoices = element.choices.map((choice, idx) => {
        if (idx !== choiceIdx) return choice;
        return { ...choice, ...updatedAttributes };
      });
    }

    updateElement(elementIdx, {
      choices: newChoices,
    });
  };

  const regularChoices = useMemo(
    () => element.choices?.filter((c) => c.id !== "other" && c.id !== "none"),
    [element.choices]
  );

  // Get the display name for the selected language (for multi-language surveys)
  const bulkEditButtonLabel = useMemo(() => {
    if (localSurvey.languages.length <= 1) {
      return t("workspace.surveys.edit.bulk_edit");
    }

    const languageCode =
      selectedLanguageCode === "default"
        ? localSurvey.languages.find((lang) => lang.default)?.language.code
        : selectedLanguageCode;

    const languageName = languageCode ? getLanguageLabel(languageCode, locale) : "";
    return `${t("workspace.surveys.edit.bulk_edit")} (${languageName})`;
  }, [localSurvey.languages, selectedLanguageCode, locale, t]);

  const addChoice = (choiceIdx?: number) => {
    setIsNew(false);

    const newChoice = {
      id: createId(),
      label: createI18nString("", surveyLanguageCodes),
    };

    if (choiceIdx !== undefined) {
      regularChoices.splice(choiceIdx + 1, 0, newChoice);
    } else {
      regularChoices.push(newChoice);
    }

    const newChoices = ensureSpecialChoicesOrder([
      ...regularChoices,
      ...element.choices.filter((c) => c.id === "other" || c.id === "none"),
    ]);

    updateElement(elementIdx, { choices: newChoices });
  };

  const addSpecialChoice = (choiceId: "other" | "none", labelText: string) => {
    if (element.choices.some((c) => c.id === choiceId)) return;

    const newChoice = {
      id: choiceId,
      label: createI18nString(labelText, surveyLanguageCodes),
    };

    const newChoices = ensureSpecialChoicesOrder([...element.choices, newChoice]);
    const nextShuffleOption = getShuffleOptionAfterAddingSpecialChoice(element.shuffleOption);

    updateElement(elementIdx, {
      choices: newChoices,
      ...(choiceId === "other" &&
        !element.otherOptionPlaceholder && {
          otherOptionPlaceholder: createI18nString(
            t("workspace.surveys.edit.please_specify"),
            surveyLanguageCodes
          ),
        }),
      ...(nextShuffleOption && { shuffleOption: nextShuffleOption }),
    });
  };

  const deleteChoice = (choiceIdx: number) => {
    const choiceToDelete = element.choices[choiceIdx].id;
    if (lock.isOptionLocked("choices", choiceToDelete)) return;

    if (choiceToDelete !== "other" && choiceToDelete !== "none") {
      const use = findOptionUse(localSurvey, element.id, choiceToDelete);
      if (use) {
        const questionIndex = use.elementIndex + 1;
        toast.error(
          use.kind === "showIf"
            ? t("workspace.surveys.edit.option_used_in_show_if_error", { questionIndex })
            : t("workspace.surveys.edit.option_used_in_logic_error", { questionIndex })
        );
        return;
      }
    }

    const newChoices = !element.choices ? [] : element.choices.filter((_, idx) => idx !== choiceIdx);
    const choiceValue = element.choices[choiceIdx].label[selectedLanguageCode];
    if (isInvalidValue === choiceValue) {
      setisInvalidValue(null);
    }

    const nextShuffleOption = getShuffleOptionAfterRemovingSpecialChoice(element.shuffleOption, newChoices);

    updateElement(elementIdx, {
      choices: newChoices,
      ...(nextShuffleOption && { shuffleOption: nextShuffleOption }),
    });
  };

  useEffect(() => {
    if (lastChoiceRef.current) {
      lastChoiceRef.current?.focus();
    }
  }, [element.choices?.length]);

  // This effect will run once on initial render, setting focus to the element input.
  useEffect(() => {
    if (isNew && elementRef.current) {
      elementRef.current.focus();
    }
  }, [isNew]);

  const specialChoices = [
    {
      id: "other",
      label: t("common.other"),
      addChoice: () => addSpecialChoice("other", t("common.other")),
      addButtonText: t("workspace.surveys.edit.add_other"),
    },
    {
      id: "none",
      label: t("common.none_of_the_above"),
      addChoice: () => addSpecialChoice("none", t("common.none_of_the_above")),
      addButtonText: t("workspace.surveys.edit.add_none_of_the_above"),
    },
  ];

  // Auto animate
  const [parent] = useAutoAnimate();

  return (
    <form>
      <ElementFormInput
        id="headline"
        value={element.headline}
        label={t("workspace.surveys.edit.question") + "*"}
        localSurvey={localSurvey}
        elementIdx={elementIdx}
        isInvalid={isInvalid}
        updateElement={updateElement}
        locale={locale}
        isStorageConfigured={isStorageConfigured}
        focusOnMount={!element.headline?.default || element.headline.default.trim() === ""}
        isExternalUrlsAllowed={isExternalUrlsAllowed}
      />

      <div ref={parent}>
        {element.subheader !== undefined && (
          <div className="inline-flex w-full items-center">
            <div className="w-full">
              <ElementFormInput
                id="subheader"
                value={element.subheader}
                label={t("common.description")}
                localSurvey={localSurvey}
                elementIdx={elementIdx}
                isInvalid={isInvalid}
                updateElement={updateElement}
                locale={locale}
                isStorageConfigured={isStorageConfigured}
                focusOnMount={!element.subheader?.default || element.subheader.default.trim() === ""}
                isExternalUrlsAllowed={isExternalUrlsAllowed}
              />
            </div>
          </div>
        )}
        {element.subheader === undefined && (
          <Button
            size="sm"
            variant="secondary"
            className="mt-3"
            type="button"
            onClick={() => {
              updateElement(elementIdx, {
                subheader: createI18nString("", surveyLanguageCodes),
              });
            }}>
            <PlusIcon className="mr-1 size-4" />
            {t("workspace.surveys.edit.add_description")}
          </Button>
        )}
      </div>

      <div className="mt-3">
        <Label htmlFor="choices">{t("workspace.surveys.edit.options")}</Label>
        <div className="mt-2" id="choices">
          <DndContext
            id="multi-choice-choices"
            onDragEnd={(event) => {
              const { active, over } = event;

              if (
                active.id === "other" ||
                over?.id === "other" ||
                active.id === "none" ||
                over?.id === "none"
              ) {
                return;
              }

              if (!active || !over) {
                return;
              }

              const activeIndex = element.choices.findIndex((choice) => choice.id === active.id);
              const overIndex = element.choices.findIndex((choice) => choice.id === over.id);

              const newChoices = [...element.choices];

              newChoices.splice(activeIndex, 1);
              newChoices.splice(overIndex, 0, element.choices[activeIndex]);

              updateElement(elementIdx, { choices: newChoices });
            }}>
            <SortableContext items={element.choices} strategy={verticalListSortingStrategy}>
              <div className="flex max-h-[34dvh] flex-col gap-2 overflow-y-auto py-1 pr-1" ref={parent}>
                {element.choices?.map((choice, choiceIdx) => (
                  <ElementOptionChoice
                    key={choice.id}
                    choice={choice}
                    choiceIdx={choiceIdx}
                    elementIdx={elementIdx}
                    updateChoice={updateChoice}
                    deleteChoice={deleteChoice}
                    addChoice={addChoice}
                    isInvalid={isInvalid}
                    localSurvey={localSurvey}
                    surveyLanguages={surveyLanguages}
                    element={element}
                    updateElement={updateElement}
                    surveyLanguageCodes={surveyLanguageCodes}
                    locale={locale}
                    isStorageConfigured={isStorageConfigured}
                    lock={lock}
                    onSetOptionHidden={onSetOptionHidden}
                  />
                ))}
              </div>
            </SortableContext>
          </DndContext>
        </div>

        <div className="mt-2">
          <div className="mt-2 flex flex-wrap items-center justify-between gap-2">
            <div className="flex flex-wrap gap-2">
              <Button size="sm" variant="secondary" type="button" onClick={() => addChoice()}>
                {t("workspace.surveys.edit.add_option")}
                <PlusIcon />
              </Button>
              {specialChoices.map((specialChoice) => {
                if (element.choices.some((c) => c.id === specialChoice.id)) return null;
                return (
                  <Button
                    size="sm"
                    key={specialChoice.id}
                    variant="secondary"
                    type="button"
                    onClick={() => specialChoice.addChoice()}>
                    {specialChoice.addButtonText}
                  </Button>
                );
              })}
              <TooltipRenderer
                shouldRender={lock.isTypeLocked}
                delayDuration={LOCK_TOOLTIP_DELAY_MS}
                tooltipContent={t("workspace.surveys.edit.lock_explanation_option_text")}
                className="max-w-xs text-xs">
                <Button
                  size="sm"
                  variant="secondary"
                  type="button"
                  disabled={lock.isTypeLocked}
                  onClick={() => setIsBulkEditOpen(true)}>
                  {bulkEditButtonLabel}
                </Button>
              </TooltipRenderer>
            </div>
            <div className="flex items-center gap-1">
              {lock.isTypeLocked && <PublishedLockNotice kind="type" />}
              <Button
                size="sm"
                variant="secondary"
                type="button"
                disabled={lock.isTypeLocked}
                onClick={() => {
                  updateElement(elementIdx, {
                    type:
                      element.type === TSurveyElementTypeEnum.MultipleChoiceMulti
                        ? TSurveyElementTypeEnum.MultipleChoiceSingle
                        : TSurveyElementTypeEnum.MultipleChoiceMulti,
                  });
                }}>
                {element.type === TSurveyElementTypeEnum.MultipleChoiceSingle
                  ? t("workspace.surveys.edit.convert_to_multiple_choice")
                  : t("workspace.surveys.edit.convert_to_single_choice")}
              </Button>
            </div>
          </div>
        </div>
      </div>

      <BulkEditOptionsModal
        isOpen={isBulkEditOpen}
        onClose={() => setIsBulkEditOpen(false)}
        regularChoices={regularChoices}
        onSave={(updatedChoices) => {
          const newChoices = ensureSpecialChoicesOrder([
            ...updatedChoices,
            ...element.choices.filter((c) => c.id === "other" || c.id === "none"),
          ]);
          updateElement(elementIdx, { choices: newChoices });
        }}
        element={element}
        localSurvey={localSurvey}
        surveyLanguageCodes={surveyLanguageCodes}
        locale={locale}
      />
    </form>
  );
};
