import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { type TJsFileUploadParams } from "@formbricks/types/js";
import { type TResponseData, type TResponseTtc } from "@formbricks/types/responses";
import { type TUploadFileConfig } from "@formbricks/types/storage";
import { type TSurveyBlock } from "@formbricks/types/surveys/blocks";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/constants";
import { type TSurveyElement, type TSurveyRankingElement } from "@formbricks/types/surveys/elements";
import { TSurveyLanguage } from "@formbricks/types/surveys/types";
import { TValidationErrorMap } from "@formbricks/types/surveys/validation-rules";
import { BackButton } from "@/components/buttons/back-button";
import { SubmitButton } from "@/components/buttons/submit-button";
import { ElementConditional } from "@/components/general/element-conditional";
import { ScrollableContainer } from "@/components/wrappers/scrollable-container";
import {
  getAutoProgressElement,
  shouldHideSubmitButtonForAutoProgress,
  shouldTriggerAutoProgress,
} from "@/lib/auto-progress";
import { type SubmitContributor, answersForValidation, createBlockSubmitRunner } from "@/lib/block-submit";
import { getLocalizedValue } from "@/lib/i18n";
import { getBlockPrefill } from "@/lib/prefill";
import { getRevealedElementIds } from "@/lib/revealed-elements";
import { type SignatureDraftStore } from "@/lib/signature-answer";
import { cn } from "@/lib/utils";
import { getFirstErrorMessage, validateBlockResponses } from "@/lib/validation/evaluator";

const AUTO_PROGRESS_SUBMIT_DELAY_MS = 350;

/**
 * Anchors are deliberately absent: they are focusable, but a link is never what a card asks of the
 * respondent. A headline or subheader may carry one in its prose (a consent element pointing at a
 * privacy policy), and that link sits *before* the element's own control in the DOM — so mount
 * focus landed on a word in the question text, ringed, reading as a highlighted suggestion
 * (ENG-2415), and gave a screen-reader user "Privacy Policy, link" as their orientation instead of
 * the question's control. Excluding `a` from `[tabindex="0"]` too keeps that uniform for an anchor
 * made focusable by hand. Nothing is left unfocused by the exclusion: every block renders its
 * Submit and/or Back button inside `root`, and the only shape without one (an auto-progress
 * element on the first block) is a radio group.
 */
const FOCUSABLE_CONTROL_SELECTOR = [
  'input:not([type="hidden"]):not([tabindex="-1"]):not(:disabled)',
  "textarea:not(:disabled)",
  "select:not(:disabled)",
  "button:not(:disabled)",
  '[tabindex="0"]:not(a)',
].join(", ");

/**
 * Focuses the first interactive control inside `root`. With `preferInvalid`,
 * controls flagged aria-invalid win. Prose links are not candidates at all (see
 * FOCUSABLE_CONTROL_SELECTOR).
 *
 * Scrolling is always left to the caller. The first control can sit *below* the card's content — a
 * CTA block has no input of its own, so its first control is the Next button rendered after the
 * element — and letting focus scroll that into view opens an overflowing card at its end instead of
 * its start (ENG-2289). The `preferInvalid` callers scroll the field they focus into view themselves.
 */
const focusFirstControl = (root: HTMLElement, preferInvalid = false): void => {
  const invalidTarget = preferInvalid
    ? root.querySelector<HTMLElement>(
        ':is(input, textarea, select)[aria-invalid="true"]:not([tabindex="-1"]):not(:disabled)'
      )
    : null;
  const target = invalidTarget ?? root.querySelector<HTMLElement>(FOCUSABLE_CONTROL_SELECTOR);
  target?.focus({ preventScroll: true });
};

interface BlockConditionalProps {
  block: TSurveyBlock;
  value: TResponseData;
  onChange: (responseData: TResponseData) => void;
  onSubmit: (data: TResponseData, ttc: TResponseTtc) => void;
  onBack: () => void;
  onFileUpload: (file: TJsFileUploadParams["file"], config?: TUploadFileConfig) => Promise<string>;
  isFirstBlock: boolean;
  isLastBlock: boolean;
  languageCode: string;
  prefilledResponseData?: TResponseData;
  skipPrefilled?: boolean;
  ttc: TResponseTtc;
  setTtc: (ttc: TResponseTtc) => void;
  surveyId: string;
  autoFocusEnabled: boolean;
  /**
   * Move focus to the block's first interactive control when the card appears.
   * True for user-initiated navigation (Next/Back/auto-progress) on any survey,
   * and for the initial card when autofocus is allowed (not an embedded widget).
   */
  shouldFocusOnMount: boolean;
  isBackButtonHidden: boolean;
  isAutoProgressingEnabled: boolean;
  onOpenExternalURL?: (url: string) => void | Promise<void>;
  dir?: "ltr" | "rtl" | "auto";
  fullSizeCards: boolean;
  isCardless?: boolean;
  surveyLanguages: TSurveyLanguage[];
  /**
   * The elements show-if leaves on this page (ENG-6931), re-evaluated by the survey as answers change.
   * Hidden elements are not rendered, validated or submitted. Absent means every element is shown.
   */
  visibleElementIds?: string[];
  /** The survey's in-memory Signature drawings, so a drawing survives leaving this card and coming back. */
  signatureDrafts: SignatureDraftStore;
}

export function BlockConditional({
  block,
  value,
  onChange,
  onSubmit,
  onBack,
  isFirstBlock,
  isLastBlock,
  languageCode,
  prefilledResponseData,
  skipPrefilled,
  ttc,
  setTtc,
  surveyId,
  onFileUpload,
  autoFocusEnabled,
  shouldFocusOnMount,
  isBackButtonHidden,
  isAutoProgressingEnabled,
  onOpenExternalURL,
  dir,
  fullSizeCards,
  isCardless = false,
  surveyLanguages,
  visibleElementIds,
  signatureDrafts,
}: Readonly<BlockConditionalProps>) {
  // What the page shows. Auto-progress and `skipPrefilled` still read `block.elements`: a block with a
  // follow-up hidden for now must not auto-submit on the answer that would reveal it.
  const elements = visibleElementIds
    ? block.elements.filter((element) => visibleElementIds.includes(element.id))
    : block.elements;
  // Track the current element being filled (for TTC tracking)
  const [currentElementId, setCurrentElementId] = useState(elements[0]?.id);

  // State to store validation errors from centralized validation
  const [elementErrors, setElementErrors] = useState<TValidationErrorMap>({});

  // Refs to store form elements for each element so we can trigger their validation
  const elementFormRefs = useRef<Map<string, HTMLFormElement>>(new Map());

  // Ref to collect TTC values synchronously (state updates are async)
  const ttcCollectorRef = useRef<TResponseTtc>({});
  const autoProgressingInFlightRef = useRef(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // A follow-up an answer on this page just revealed is scrolled into view (ENG-6931), above the
  // card's scroll-down button (the container's scroll padding), instead of appearing under it.
  const shownElementIdsRef = useRef<string[] | null>(null);
  const shownElementIdsKey = elements.map((element) => element.id).join("|");
  useEffect(() => {
    const shownIds = shownElementIdsKey === "" ? [] : shownElementIdsKey.split("|");
    const revealed = getRevealedElementIds(shownElementIdsRef.current, shownIds);
    shownElementIdsRef.current = shownIds;
    const lastRevealed = revealed.at(-1);
    if (lastRevealed === undefined) return;
    requestAnimationFrame(() => {
      elementFormRefs.current.get(lastRevealed)?.scrollIntoView({ block: "nearest" });
    });
  }, [shownElementIdsKey]);
  // Elements that produce their answer on Next (the Signature uploads its image then), and the guard
  // that keeps a second press from starting a second upload while the first is still running.
  const submitContributorsRef = useRef(new Map<string, SubmitContributor>());
  const registerSubmitContributor = useCallback(
    (elementId: string, contributor: SubmitContributor | null) => {
      if (contributor) submitContributorsRef.current.set(elementId, contributor);
      else submitContributorsRef.current.delete(elementId);
    },
    []
  );
  const [isSubmitting, setIsSubmitting] = useState(false);
  const isMountedRef = useRef(true);
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  // Keep the handler from the visit that started the upload. Reading the latest handler could submit
  // these old answers after the respondent leaves and returns to the same block.
  const pendingSubmitRef = useRef(onSubmit);
  const pendingTtcRef = useRef<TResponseTtc>({});
  const refocusSubmitRef = useRef(false);
  const [submitRunner] = useState(() =>
    createBlockSubmitRunner({
      getContributors: () => submitContributorsRef.current,
      onSubmit: (answers) => {
        pendingSubmitRef.current(answers, pendingTtcRef.current);
      },
      onFailure: (failedElementId) => {
        // The Next button is locked while the upload runs; once it is free again it takes focus back,
        // so a keyboard or screen-reader user is not left on <body>.
        refocusSubmitRef.current = true;
        const form = elementFormRefs.current.get(failedElementId);
        const scrollTarget = form?.querySelector("[data-element-input]") ?? form;
        scrollTarget?.scrollIntoView({ behavior: "smooth", block: "center" });
      },
      onBusyChange: setIsSubmitting,
      isMounted: () => isMountedRef.current,
      onError: (error) => {
        console.error("[Formbricks] Submitting the card failed", error);
      },
    })
  );
  useEffect(() => {
    if (isSubmitting || !refocusSubmitRef.current) return;
    refocusSubmitRef.current = false;
    containerRef.current
      ?.querySelector<HTMLElement>('[data-fb-part="button-primary"]')
      ?.focus({ preventScroll: true });
  }, [isSubmitting]);

  // Screen-reader/keyboard users continue right where they act: when the card
  // appears after user navigation (or on an autofocus-allowed initial render),
  // focus its first control instead of dropping focus to the body, which made
  // VoiceOver re-announce the whole survey dialog on every card change.
  useLayoutEffect(() => {
    if (!shouldFocusOnMount) return;

    // Defer so the card's content (and any card transition) has rendered.
    let animationFrameId: number | undefined;
    const timeoutId = setTimeout(() => {
      animationFrameId = requestAnimationFrame(() => {
        const container = containerRef.current;
        // The respondent may already have chosen a control while this callback was pending.
        if (container && !container.contains(document.activeElement)) focusFirstControl(container);
      });
    }, 0);

    return () => {
      clearTimeout(timeoutId);
      if (animationFrameId !== undefined) cancelAnimationFrame(animationFrameId);
    };
  }, [shouldFocusOnMount]);
  const autoProgressElement = getAutoProgressElement(block.elements, isAutoProgressingEnabled);
  const shouldHideSubmitButton = shouldHideSubmitButtonForAutoProgress(
    block.elements,
    isAutoProgressingEnabled,
    value
  );

  // Handle change for an individual element
  const handleElementChange = (elementId: string, responseData: TResponseData) => {
    // If user moved to a different element, we should track it
    if (elementId !== currentElementId) {
      setCurrentElementId(elementId);
    }
    // Clear error for this element when user makes a change
    if (elementErrors[elementId]) {
      setElementErrors((prev: TValidationErrorMap) => {
        const updated = { ...prev };
        delete updated[elementId];
        return updated;
      });
    }
    const mergedValue = { ...value, ...responseData };
    const blockResponses = elements.reduce<TResponseData>((acc, element) => {
      const elementValue = mergedValue[element.id];
      if (elementValue !== undefined) {
        acc[element.id] = elementValue;
      }
      return acc;
    }, {});

    // Pass up only this element's change; `Survey` merges it into the latest answers. Sending
    // `mergedValue` would write back this render's copy of every other answer, which is stale
    // when the change comes from a file upload that finished after the respondent kept editing.
    onChange(responseData);

    if (
      shouldTriggerAutoProgress({
        changedElementId: elementId,
        mergedValue,
        autoProgressElement,
        isAlreadyInFlight: autoProgressingInFlightRef.current,
      })
    ) {
      autoProgressingInFlightRef.current = true;
      // The selection is committed and the card is about to leave: drop focus now so
      // the focus ring doesn't linger on the answered option during the submit delay
      // (it read as a flashing ring). The next card focuses its first control on mount.
      const active = document.activeElement;
      if (active instanceof HTMLElement) active.blur();
      // Defer submission so element-level change handlers can finalize TTC updates first.
      setTimeout(() => {
        try {
          const blockTtc = collectTtcValues();
          onSubmit(blockResponses, blockTtc);
        } finally {
          autoProgressingInFlightRef.current = false;
        }
      }, AUTO_PROGRESS_SUBMIT_DELAY_MS);
    }
  };

  // Handler to collect TTC values synchronously (called from element form submissions)
  const handleTtcCollect = (elementId: string, elementTtc: number) => {
    ttcCollectorRef.current[elementId] = elementTtc;
  };

  // Handle prefilling at block level (both skipPrefilled and regular prefilling)
  useEffect(() => {
    // Every element of the block, not only those shown now: a prefill that reveals a required
    // follow-up keeps the page open for it (`getBlockPrefill`).
    const { data: prefilledData, autoSubmit } = getBlockPrefill(block, prefilledResponseData, skipPrefilled);
    if (Object.keys(prefilledData).length === 0) return;

    // Apply all prefilled values in one atomic operation
    onChange(prefilledData);

    if (autoSubmit) {
      const prefilledTtc: TResponseTtc = {};
      block.elements.forEach((element) => {
        prefilledTtc[element.id] = 0; // 0 TTC for prefilled/skipped questions
      });
      setTtc({ ...ttc, ...prefilledTtc });

      // Auto-submit the entire block (skip to next)
      setTimeout(() => {
        onSubmit(prefilledData, prefilledTtc);
      }, 0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- Only run once when block mounts
  }, []);

  // Validate ranking element
  const validateRankingElement = (
    element: TSurveyRankingElement,
    response: unknown,
    form: HTMLFormElement
  ): boolean => {
    const isRequired = element.required;
    const isValueArray = Array.isArray(response);
    const atLeastOneRanked = isValueArray && response.length >= 1;

    // If required: at least 1 option must be ranked
    if (isRequired && (!isValueArray || !atLeastOneRanked)) {
      form.requestSubmit();
      return false;
    }

    // If not required: allow partial ranking (some items ranked, some not)
    // No validation needed - user can proceed with any number of ranked items (including 0)

    return true;
  };

  // Check if response is empty
  const isEmptyResponse = (response: unknown): boolean => {
    return (
      response === undefined ||
      response === null ||
      response === "" ||
      (Array.isArray(response) && response.length === 0) ||
      (typeof response === "object" && !Array.isArray(response) && Object.keys(response).length === 0)
    );
  };

  // Validate a single element's form
  const validateElementForm = (
    element: TSurveyElement,
    form: HTMLFormElement,
    answers: TResponseData
  ): boolean => {
    const response = answers[element.id];

    if (element.type !== TSurveyElementTypeEnum.CTA && !form.checkValidity()) {
      form.requestSubmit();
      return false;
    }

    if (
      element.type === TSurveyElementTypeEnum.Address ||
      element.type === TSurveyElementTypeEnum.ContactInfo
    ) {
      return true;
    }

    // Custom validation for ranking questions
    if (element.type === TSurveyElementTypeEnum.Ranking && !validateRankingElement(element, response, form)) {
      return false;
    }

    // Custom validation for matrix questions
    if (element.type === TSurveyElementTypeEnum.Matrix) {
      // Required means at least 1 row must be answered
      if (element.required && (!response || Object.keys(response).length === 0)) {
        form.requestSubmit();
        return false;
      }
    }

    // For other element types, check if required fields are empty
    // CTA elements should not block navigation even if marked required (as they are informational)
    if (element.type !== TSurveyElementTypeEnum.CTA) {
      if (element.required && isEmptyResponse(response)) {
        form.requestSubmit();
        return false;
      }
    }

    return true;
  };

  // Find the first invalid form
  const findFirstInvalidForm = (answers: TResponseData): HTMLFormElement | null => {
    let firstInvalidForm: HTMLFormElement | null = null;

    for (const element of elements) {
      const form = elementFormRefs.current.get(element.id);
      if (form && !validateElementForm(element, form, answers)) {
        firstInvalidForm ??= form;
      }
    }

    return firstInvalidForm;
  };

  // Collect TTC values from forms
  const collectTtcValues = (): TResponseTtc => {
    // Clear the TTC collector before collecting new values
    ttcCollectorRef.current = {};

    // Call each form's submit method to trigger TTC calculation
    elements.forEach((element) => {
      const form = elementFormRefs.current.get(element.id);
      if (form) {
        form.requestSubmit();
      }
    });

    // Collect TTC from the ref (populated synchronously by form submissions)
    const blockTtc: TResponseTtc = {};
    elements.forEach((element) => {
      if (ttcCollectorRef.current[element.id] !== undefined) {
        blockTtc[element.id] = ttcCollectorRef.current[element.id];
      } else if (ttc[element.id] !== undefined) {
        blockTtc[element.id] = ttc[element.id];
      }
    });

    return blockTtc;
  };

  // Collect responses for all elements in this block
  const collectBlockResponses = (answers: TResponseData = value): TResponseData => {
    const blockResponses: TResponseData = {};
    elements.forEach((element) => {
      if (answers[element.id] !== undefined) {
        blockResponses[element.id] = answers[element.id];
      }
    });
    return blockResponses;
  };

  const handleBlockSubmit = (e?: Event) => {
    if (e) {
      e.preventDefault();
    }
    // A Signature that is drawn but not uploaded yet counts as answered for validation, and one that was
    // just cleared counts as empty.
    const answers = answersForValidation(value, submitContributorsRef.current);

    // Run centralized validation for elements that support it
    const errorMap = validateBlockResponses(elements, answers, languageCode);

    // Check if there are any validation errors from centralized validation
    const hasValidationErrors = Object.keys(errorMap).length > 0;

    if (hasValidationErrors) {
      setElementErrors(errorMap);

      // Find the first element with an error, scroll to its input area (not the headline)
      // and move focus to its first invalid control so keyboard users can fix it directly.
      const firstErrorElementId = Object.keys(errorMap)[0];
      const form = elementFormRefs.current.get(firstErrorElementId);
      if (form) {
        const scrollTarget = form.querySelector("[data-element-input]") ?? form;
        scrollTarget.scrollIntoView({ behavior: "smooth", block: "center" });
        // Defer so aria-invalid from the new error state is in the DOM.
        requestAnimationFrame(() => {
          focusFirstControl(form, true);
        });
      }
      return;
    }

    // Also run legacy validation for elements not yet migrated to centralized validation
    const firstInvalidForm = findFirstInvalidForm(answers);
    if (firstInvalidForm) {
      const scrollTarget = firstInvalidForm.querySelector("[data-element-input]") ?? firstInvalidForm;
      scrollTarget.scrollIntoView({ behavior: "smooth", block: "center" });
      requestAnimationFrame(() => {
        focusFirstControl(firstInvalidForm, true);
      });
      return;
    }

    // Clear any previous errors
    setElementErrors({});

    // Collect TTC and responses, then submit
    const blockTtc = collectTtcValues();

    if (submitContributorsRef.current.size === 0) {
      onSubmit(collectBlockResponses(), blockTtc);
      return;
    }
    // A press while an earlier one is still uploading does nothing (the runner guards it too).
    if (isSubmitting) return;

    // Upload on Next: elements that produce their answer now (the Signature renders and uploads its
    // image) are awaited before the block advances. A failure leaves the card as it is, with the
    // element's own error showing, and pressing Next again retries. What advances is the snapshot that
    // was just validated, never the card's state after the upload.
    pendingSubmitRef.current = onSubmit;
    pendingTtcRef.current = blockTtc;
    submitRunner.run(collectBlockResponses(answers));
  };

  const isActionRowSticky = fullSizeCards && !isCardless;

  return (
    <div ref={containerRef} className={cn("space-y-6", fullSizeCards ? "h-full" : "")}>
      {/* Scrollable container for the entire block */}
      <ScrollableContainer fullSizeCards={fullSizeCards} disableInternalScroll={isCardless}>
        <div className={isActionRowSticky ? undefined : "space-y-6"}>
          {/* While Next uploads, the card's other inputs are read-only: the answers sent are the ones that were
              just validated, so an edit made now would be silently dropped. No margin utility: it would
              beat the space-y-6 gap above the action row. The preflight already zeroes a fieldset's margin. */}
          <fieldset disabled={isSubmitting} className="min-w-0 space-y-6 border-0 p-0">
            {elements.map((element, index) => {
              const isFirstElement = index === 0;

              return (
                <ElementConditional
                  key={element.id}
                  surveyLanguages={surveyLanguages}
                  element={element}
                  value={value[element.id]}
                  onChange={(responseData) => handleElementChange(element.id, responseData)}
                  onFileUpload={onFileUpload}
                  languageCode={languageCode}
                  ttc={ttc}
                  setTtc={setTtc}
                  surveyId={surveyId}
                  autoFocusEnabled={autoFocusEnabled && isFirstElement}
                  currentElementId={currentElementId}
                  onOpenExternalURL={onOpenExternalURL}
                  dir={dir}
                  formRef={(ref) => {
                    if (ref) {
                      elementFormRefs.current.set(element.id, ref);
                    } else {
                      elementFormRefs.current.delete(element.id);
                    }
                  }}
                  onTtcCollect={handleTtcCollect}
                  errorMessage={getFirstErrorMessage(elementErrors, element.id)}
                  signatureDrafts={signatureDrafts}
                  registerSubmitContributor={registerSubmitContributor}
                  disabled={isSubmitting}
                />
              );
            })}
          </fieldset>

          <div
            className={cn(
              "flex w-full flex-row-reverse justify-between",
              // The gap lives in the row's own padding: a margin on the elements scrolls away and
              // leaves the sticky row flush against the last input.
              isActionRowSticky ? "bg-survey-bg sticky bottom-0 pt-6" : ""
            )}>
            <div>
              {shouldHideSubmitButton ? (
                // Keep layout symmetry for Back button positioning (LTR/RTL).
                <div aria-hidden="true" className="mb-1 h-(--fb-button-height)" />
              ) : (
                <SubmitButton
                  buttonLabel={
                    block.buttonLabel ? getLocalizedValue(block.buttonLabel, languageCode) : undefined
                  }
                  isLastQuestion={isLastBlock}
                  onClick={handleBlockSubmit}
                  disabled={isSubmitting}
                  tabIndex={0}
                />
              )}
            </div>
            {!isFirstBlock && !isBackButtonHidden && (
              <BackButton
                backButtonLabel={
                  block.backButtonLabel ? getLocalizedValue(block.backButtonLabel, languageCode) : undefined
                }
                onClick={onBack}
                disabled={isSubmitting}
                tabIndex={0}
              />
            )}
          </div>
        </div>
      </ScrollableContainer>
    </div>
  );
}
