"use client";

import * as Collapsible from "@radix-ui/react-collapsible";
import { CheckIcon, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useMemo, useState } from "react";
import { Trans, useTranslation } from "react-i18next";
import { ActionClass, OrganizationRole } from "@formbricks/database/prisma-browser";
import { TActionClass } from "@formbricks/types/action-classes";
import { TSurvey } from "@formbricks/types/surveys/types";
import { cn } from "@/lib/cn";
import { getAccessFlags } from "@/lib/membership/utils";
import { OpenedByCreatives } from "@/modules/ee/creatives/components/survey-side/opened-by-creatives";
import type { TSurveyLinkedCreative } from "@/modules/ee/creatives/lib/survey-side";
import { getTeamPermissionFlags } from "@/modules/ee/teams/utils/teams";
import { TTeamPermission } from "@/modules/ee/teams/workspace-teams/types/team";
import { ShowConditionsBlock } from "@/modules/show-conditions/components/show-conditions-block";
import { AddActionModal } from "@/modules/survey/editor/components/add-action-modal";
import { ActionClassInfo } from "@/modules/ui/components/action-class-info";
import { AdvancedOptionToggle } from "@/modules/ui/components/advanced-option-toggle";
import { Button } from "@/modules/ui/components/button";
import { Input } from "@/modules/ui/components/input";
import { TooltipRenderer } from "@/modules/ui/components/tooltip";
import { ACTION_TYPE_ICON_LOOKUP } from "@/modules/workspaces/settings/(setup)/app-connection/utils";
import { ActionDetailModal } from "@/modules/workspaces/settings/(setup)/components/ActionDetailModal";

interface WhenToSendCardProps {
  localSurvey: TSurvey;
  setLocalSurvey: React.Dispatch<React.SetStateAction<TSurvey>>;
  workspaceId: string;
  propActionClasses: ActionClass[];
  membershipRole?: OrganizationRole;
  workspacePermission: TTeamPermission | null;
  /** A save or publish was just blocked because this card has no trigger (ENG-2581). */
  hasError?: boolean;
  /** The linked creatives, which open the survey on every click whatever its actions (ENG-3579). */
  openedByCreatives?: readonly TSurveyLinkedCreative[];
}

const NO_CREATIVES: readonly TSurveyLinkedCreative[] = [];

/**
 * The card's open state, adjusted during render: an app survey starts expanded, switching to a link
 * survey collapses it, and a missing-trigger error appearing expands it — a collapsed card cannot show
 * the user what to fix.
 */
const useWhenToSendCardOpen = (surveyType: TSurvey["type"], showError: boolean) => {
  const [open, setOpen] = useState(surveyType === "app");

  const [seenSurveyType, setSeenSurveyType] = useState(surveyType);
  if (surveyType !== seenSurveyType) {
    setSeenSurveyType(surveyType);
    if (surveyType === "link") setOpen(false);
  }

  const [wasShowingError, setWasShowingError] = useState(false);
  if (showError !== wasShowingError) {
    setWasShowingError(showError);
    if (showError) setOpen(true);
  }

  return [open, setOpen] as const;
};

export const WhenToSendCard = ({
  workspaceId,
  localSurvey,
  setLocalSurvey,
  propActionClasses,
  membershipRole,
  workspacePermission,
  hasError = false,
  openedByCreatives = NO_CREATIVES,
}: Readonly<WhenToSendCardProps>) => {
  const { t } = useTranslation();
  const [isAddActionModalOpen, setAddActionModalOpen] = useState(false);
  const [isEditActionModalOpen, setEditActionModalOpen] = useState(false);
  const [editingActionClass, setEditingActionClass] = useState<TActionClass | null>(null);
  const [actionClasses, setActionClasses] = useState<ActionClass[]>(propActionClasses);
  const [randomizerToggle, setRandomizerToggle] = useState(Boolean(localSurvey.displayPercentage));

  const { isMember } = getAccessFlags(membershipRole);
  const { hasReadAccess } = getTeamPermissionFlags(workspacePermission);

  const isReadOnly = isMember && hasReadAccess;

  const autoClose = localSurvey.autoClose !== null;
  const delay = localSurvey.delay !== 0;

  const handleRemoveTriggerEvent = (idx: number) => {
    const updatedSurvey = { ...localSurvey };
    updatedSurvey.triggers = [...localSurvey.triggers.slice(0, idx), ...localSurvey.triggers.slice(idx + 1)];
    setLocalSurvey(updatedSurvey);
  };

  const handleEditTriggerEvent = (actionClass: TActionClass) => {
    setEditingActionClass(actionClass);
    setEditActionModalOpen(true);
  };

  const handleActionUpdated = (updatedAction: TActionClass) => {
    setActionClasses((prevActionClasses) =>
      prevActionClasses.map((actionClass) =>
        actionClass.id === updatedAction.id ? updatedAction : actionClass
      )
    );
    setLocalSurvey((prevSurvey) => ({
      ...prevSurvey,
      triggers: prevSurvey.triggers.map((trigger) =>
        trigger.actionClass.id === updatedAction.id ? { ...trigger, actionClass: updatedAction } : trigger
      ),
    }));
  };

  const handleAutoCloseToggle = () => {
    if (autoClose) {
      const updatedSurvey = { ...localSurvey, autoClose: null };
      setLocalSurvey(updatedSurvey);
    } else {
      const updatedSurvey = { ...localSurvey, autoClose: 10 };
      setLocalSurvey(updatedSurvey);
    }
  };

  const handleKeepEndingCardOpenToggle = () => {
    setLocalSurvey({ ...localSurvey, keepEndingCardOpen: !localSurvey.keepEndingCardOpen });
  };

  const handleDelayToggle = () => {
    if (delay) {
      const updatedSurvey = { ...localSurvey, delay: 0 };
      setLocalSurvey(updatedSurvey);
    } else {
      const updatedSurvey = { ...localSurvey, delay: 5 };
      setLocalSurvey(updatedSurvey);
    }
  };

  const handleDisplayPercentageToggle = () => {
    if (localSurvey.displayPercentage) {
      const updatedSurvey = { ...localSurvey, displayPercentage: null };
      setLocalSurvey(updatedSurvey);
    } else {
      const updatedSurvey = { ...localSurvey, displayPercentage: 50 };
      setLocalSurvey(updatedSurvey);
    }
    setRandomizerToggle(!randomizerToggle);
  };

  const handleInputSeconds = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = parseInt(e.target.value);

    if (value < 1 || Number.isNaN(value)) {
      value = 0;
    }

    const updatedSurvey = { ...localSurvey, autoClose: value };
    setLocalSurvey(updatedSurvey);
  };

  const handleTriggerDelay = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = parseInt(e.target.value);

    if (value < 1 || Number.isNaN(value)) {
      value = 0;
    }

    const updatedSurvey = { ...localSurvey, delay: value };
    setLocalSurvey(updatedSurvey);
  };

  const handleRandomizerInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = parseFloat(e.target.value);

    if (Number.isNaN(value)) {
      value = 0.01;
    }

    if (value < 0.01) value = 0.01;
    if (value > 100) value = 100;

    // Round value to two decimal places. eg: 10.555(and higher like 10.556) -> 10.56 and 10.554(and lower like 10.553) ->10.55
    value = Math.round(value * 100) / 100;

    const updatedSurvey = { ...localSurvey, displayPercentage: value };
    setLocalSurvey(updatedSurvey);
  };

  // Auto animate

  const containsEmptyTriggers = useMemo(() => {
    return !localSurvey.triggers || !localSurvey.triggers.length || !localSurvey.triggers[0];
  }, [localSurvey]);

  // A creative opening the survey is what displays it, so the card isn't waiting for an action.
  const isWaitingForOpener = containsEmptyTriggers && openedByCreatives.length === 0;

  // Read at render time rather than mirrored into state, so adding a trigger clears the error the
  // moment the survey has one — nothing has to remember to reset a flag.
  const showError = hasError && containsEmptyTriggers;

  const [open, setOpen] = useWhenToSendCardOpen(localSurvey.type, showError);

  if (localSurvey.type === "link") {
    return null; // Hide card completely
  }

  return (
    <>
      <Collapsible.Root
        open={open}
        onOpenChange={(openState) => {
          if (localSurvey.type !== "link") {
            setOpen(openState);
          }
        }}
        className={cn(
          "w-full rounded-lg border bg-white",
          showError ? "border-red-400" : "border-slate-300"
        )}>
        <Collapsible.CollapsibleTrigger
          asChild
          className="h-full w-full cursor-pointer rounded-lg hover:bg-slate-50"
          id="whenToSendCardTrigger"
          aria-invalid={showError}>
          <button type="button" className="inline-flex px-4 py-4 text-left">
            <div className="flex items-center pr-5 pl-2">
              {isWaitingForOpener ? (
                <div
                  className={cn(
                    "size-7 rounded-full border",
                    showError ? "border-red-400 bg-red-100" : "border-amber-500 bg-amber-50"
                  )}
                />
              ) : (
                <CheckIcon
                  strokeWidth={3}
                  className="size-7 rounded-full border border-green-300 bg-green-100 p-1.5 text-green-600"
                />
              )}
            </div>

            <div>
              <p className="font-semibold text-slate-800">{t("workspace.surveys.edit.survey_trigger")}</p>
              <p className={cn("mt-1 text-sm", showError ? "text-red-600" : "text-slate-500")}>
                {showError
                  ? t("workspace.surveys.edit.please_set_a_survey_trigger")
                  : t("workspace.surveys.edit.choose_the_actions_which_trigger_the_survey")}
              </p>
            </div>
          </button>
        </Collapsible.CollapsibleTrigger>

        <Collapsible.CollapsibleContent className="flex flex-col overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
          <hr className="py-1 text-slate-600" />

          <div className="px-3 pt-1 pb-3">
            {openedByCreatives.length > 0 && (
              <div className="mb-3 rounded-lg border border-slate-300 bg-slate-50 p-4">
                <OpenedByCreatives workspaceId={workspaceId} creatives={openedByCreatives} />
              </div>
            )}
            <div className="filter-scrollbar flex flex-col gap-4 overflow-auto rounded-lg border border-slate-300 bg-slate-50 p-4">
              <p className="text-sm font-semibold text-slate-800">
                {t("workspace.surveys.edit.trigger_survey_when_one_of_the_actions_is_fired")}
              </p>

              {localSurvey.triggers.filter(Boolean).map((trigger, idx) => {
                return (
                  <div className="flex items-center gap-2" key={trigger.actionClass.id}>
                    {idx !== 0 && <p className="ml-1 text-sm font-bold text-slate-700">or</p>}
                    <div
                      key={trigger.actionClass.id}
                      className="flex grow items-center justify-between rounded-md border border-slate-300 bg-white p-2 px-3">
                      <div>
                        <div className="mt-1 flex items-center">
                          <div className="mr-1.5 size-4 text-slate-600">
                            {ACTION_TYPE_ICON_LOOKUP[trigger.actionClass.type]}
                          </div>

                          <h4 className="text-sm font-semibold text-slate-600">{trigger.actionClass.name}</h4>
                        </div>
                        <ActionClassInfo actionClass={trigger.actionClass} />
                      </div>
                      {isReadOnly ? null : (
                        <TooltipRenderer tooltipContent={t("common.edit")}>
                          <Button
                            variant="secondary"
                            size="icon"
                            aria-label={t("common.edit")}
                            onClick={() => handleEditTriggerEvent(trigger.actionClass)}>
                            <PencilIcon />
                          </Button>
                        </TooltipRenderer>
                      )}
                    </div>
                    <TooltipRenderer tooltipContent={t("common.delete")}>
                      <Button
                        variant="outline"
                        className="bg-white"
                        size="icon"
                        aria-label={t("common.delete")}
                        onClick={() => handleRemoveTriggerEvent(idx)}>
                        <Trash2Icon />
                      </Button>
                    </TooltipRenderer>
                  </div>
                );
              })}

              <div>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => {
                    setAddActionModalOpen(true);
                  }}>
                  <PlusIcon className="mr-2 size-4" />
                  {t("common.add_action")}
                </Button>
              </div>

              {/* Inside the trigger box, so it reads as one rule: trigger AND conditions (ENG-3687). */}
              <ShowConditionsBlock
                value={localSurvey.showConditions ?? null}
                onChange={(showConditions) => setLocalSurvey((survey) => ({ ...survey, showConditions }))}
                isReadOnly={isReadOnly}
              />
            </div>

            {/* Survey Display Settings */}
            <div className="mt-8 mb-4 space-y-1 px-4">
              <h3 className="font-semibold text-slate-800">
                {t("workspace.surveys.edit.survey_display_settings")}
              </h3>
              <p className="text-sm text-slate-500">
                {t("workspace.surveys.edit.add_a_delay_or_auto_close_the_survey")}
              </p>
            </div>
            <AdvancedOptionToggle
              htmlId="delay"
              isChecked={delay}
              onToggle={handleDelayToggle}
              title={t("workspace.surveys.edit.add_delay_before_showing_survey")}
              description={t(
                "workspace.surveys.edit.wait_a_few_seconds_after_the_trigger_before_showing_the_survey"
              )}
              childBorder={true}>
              <div className="flex w-full cursor-pointer items-center rounded-lg border bg-slate-50 p-4">
                <div>
                  <p className="text-sm font-semibold text-slate-700">
                    <Trans
                      i18nKey="workspace.surveys.edit.wait_n_seconds_before_showing_the_survey"
                      components={{
                        delayInput: (
                          <Input
                            type="number"
                            min="0"
                            id="triggerDelay"
                            value={localSurvey.delay.toString()}
                            onChange={(e) => handleTriggerDelay(e)}
                            className="mr-2 ml-2 inline w-16 bg-white text-center text-sm"
                          />
                        ),
                      }}
                    />
                  </p>
                </div>
              </div>
            </AdvancedOptionToggle>
            <AdvancedOptionToggle
              htmlId="autoClose"
              isChecked={autoClose}
              onToggle={handleAutoCloseToggle}
              title={t("workspace.surveys.edit.auto_close_on_inactivity")}
              description={t(
                "workspace.surveys.edit.automatically_close_the_survey_if_the_user_does_not_respond_after_certain_number_of_seconds"
              )}
              childBorder={true}>
              <label htmlFor="autoCloseSeconds" className="cursor-pointer p-4">
                <p className="text-sm font-semibold text-slate-700">
                  <Trans
                    i18nKey="workspace.surveys.edit.automatically_close_survey_after_n_seconds_if_no_response"
                    components={{
                      autoCloseInput: (
                        <Input
                          type="number"
                          min="1"
                          id="autoCloseSeconds"
                          value={localSurvey.autoClose?.toString()}
                          onChange={(e) => handleInputSeconds(e)}
                          className="mx-2 inline w-16 bg-white text-center text-sm"
                        />
                      ),
                    }}
                  />
                </p>
              </label>
            </AdvancedOptionToggle>
            <AdvancedOptionToggle
              htmlId="keepEndingCardOpen"
              isChecked={localSurvey.keepEndingCardOpen ?? false}
              onToggle={handleKeepEndingCardOpenToggle}
              title={t("workspace.surveys.edit.keep_ending_card_open")}
              description={t("workspace.surveys.edit.keep_ending_card_open_description")}
            />
            <AdvancedOptionToggle
              htmlId="randomizer"
              isChecked={randomizerToggle}
              onToggle={handleDisplayPercentageToggle}
              title={t("workspace.surveys.edit.show_survey_to_users")}
              description={t("workspace.surveys.edit.only_display_the_survey_to_a_subset_of_the_users")}
              childBorder={true}>
              <label htmlFor="small-range" className="cursor-pointer p-4">
                <p className="text-sm font-semibold text-slate-700">
                  {t("workspace.surveys.edit.show_to_x_percentage_of_targeted_users", {
                    percentage: localSurvey.displayPercentage,
                  })}
                  <Input
                    id="small-range"
                    type="number"
                    step="0.01"
                    min="0.01"
                    max="100"
                    value={localSurvey.displayPercentage ?? ""}
                    onChange={handleRandomizerInput}
                    className="mx-2 inline w-20 bg-white text-center text-sm"
                  />
                </p>
              </label>
            </AdvancedOptionToggle>
          </div>
        </Collapsible.CollapsibleContent>
      </Collapsible.Root>
      <AddActionModal
        workspaceId={workspaceId}
        open={isAddActionModalOpen}
        setOpen={setAddActionModalOpen}
        actionClasses={actionClasses}
        setActionClasses={setActionClasses}
        isReadOnly={isReadOnly}
        localSurvey={localSurvey}
        setLocalSurvey={setLocalSurvey}
      />
      {editingActionClass ? (
        <ActionDetailModal
          open={isEditActionModalOpen}
          setOpen={setEditActionModalOpen}
          actionClass={editingActionClass}
          actionClasses={actionClasses}
          isReadOnly={isReadOnly}
          hideDelete
          hideActivityTab
          currentSurveyId={localSurvey.id}
          onActionUpdated={handleActionUpdated}
        />
      ) : null}
    </>
  );
};
