import type { TFunction } from "i18next";
import type { TResponseData, TResponseDataValue } from "@formbricks/types/responses";
import type { TSurveyElement } from "@formbricks/types/surveys/elements";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import { getElementOptionsNotShownFromRecord } from "@formbricks/types/surveys/not-shown";
import {
  type TElementOptionsNotShown,
  getElementOptionsNotShown,
  getOptionListKeys,
  withOptionsShown,
} from "@formbricks/types/surveys/show-if";
import type {
  TAddressField,
  TContactInfoField,
  TValidationError,
  TValidationErrorMap,
  TValidationResult,
  TValidationRule,
} from "@formbricks/types/surveys/validation-rules";
import { getLocalizedValue, getTranslations } from "@/lib/i18n";
import { dropOptionsFromAnswer } from "@/lib/option-answers";
import { type TValidationOptions, validators } from "./validators";

/**
 * Check if a value is empty
 */
const isEmpty = (value: TResponseDataValue): boolean => {
  return (
    value === undefined ||
    value === null ||
    value === "" ||
    (Array.isArray(value) && value.length === 0) ||
    (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0)
  );
};

/**
 * Create a required field error
 */
const createRequiredError = (t: TFunction): TValidationError => {
  return {
    ruleId: "required",
    ruleType: "minLength", // Structural field only - required is not a validation rule
    message: t("errors.please_fill_out_this_field"),
  };
};

/**
 * Create an invalid-option error (value not among a choice element's configured options)
 */
const createInvalidOptionError = (t: TFunction): TValidationError => {
  return {
    ruleId: "invalidOption",
    ruleType: "minLength", // Structural field only - choice membership is not a configurable rule
    message: t("errors.invalid_format"),
  };
};

/**
 * Get field label for address/contact info elements
 */
const getFieldLabel = (
  element: TSurveyElement,
  field: TAddressField | TContactInfoField | undefined,
  languageCode: string
): string | undefined => {
  if (!field) return undefined;

  if (element.type === TSurveyElementTypeEnum.Address && "addressLine1" in element) {
    const fieldConfig = element[field as TAddressField];
    if (fieldConfig && "placeholder" in fieldConfig) {
      return getLocalizedValue(fieldConfig.placeholder, languageCode);
    }
  }

  if (element.type === TSurveyElementTypeEnum.ContactInfo && "firstName" in element) {
    const fieldConfig = element[field as TContactInfoField];
    if (fieldConfig && "placeholder" in fieldConfig) {
      return getLocalizedValue(fieldConfig.placeholder, languageCode);
    }
  }

  return undefined;
};

/**
 * Strip trailing whitespace and colons from a field label.
 *
 * The label comes from the author's placeholder, which often already ends with a colon
 * ("Nombre:"), so the separator we append would otherwise render a double colon. Scanning
 * backwards keeps this linear in the label's length.
 */
const stripTrailingColon = (label: string): string => {
  let end = label.length;
  while (end > 0) {
    const char = label[end - 1];
    if (char !== ":" && char !== "：" && char.trim() !== "") break;
    end--;
  }
  return label.slice(0, end);
};

/**
 * Get default error message from rule or validator
 */
const getDefaultErrorMessage = (
  rule: TValidationRule,
  element: TSurveyElement,
  languageCode: string,
  t: TFunction
): string => {
  const validator = validators[rule.type];
  if (!validator) {
    return t("errors.invalid_format");
  }

  const baseMessage = validator.getDefaultMessage(rule.params, element, t);

  // For field-specific validation, prepend the field name
  if (rule.field) {
    const fieldLabel = getFieldLabel(element, rule.field, languageCode);
    const normalizedLabel = fieldLabel ? stripTrailingColon(fieldLabel) : undefined;
    if (normalizedLabel) {
      return `${normalizedLabel}: ${baseMessage}`;
    }
  }

  return baseMessage;
};

/**
 * Validate required field for ranking elements
 */
const validateRequiredRanking = (value: TResponseDataValue, t: TFunction): TValidationError | null => {
  const isValueArray = Array.isArray(value);
  const atLeastOneRanked = isValueArray && value.length >= 1;
  if (isEmpty(value) || !atLeastOneRanked) {
    return createRequiredError(t);
  }
  return null;
};

/**
 * Validate required field for matrix elements
 * Required means: at least 1 row must be answered
 */
const validateRequiredMatrix = (
  value: TResponseDataValue,
  element: TSurveyElement,
  t: TFunction
): TValidationError | null => {
  if (isEmpty(value)) {
    return createRequiredError(t);
  }
  if (typeof value === "object" && !Array.isArray(value) && value !== null && "rows" in element) {
    const answeredRows = Object.values(value).filter((v) => v !== "" && v !== null && v !== undefined).length;
    // Required means at least 1 row must be answered
    if (answeredRows === 0) {
      return createRequiredError(t);
    }
  }
  return null;
};

const validateMultiSelectOtherValue = (
  element: TSurveyElement,
  value: TResponseDataValue,
  t: TFunction
): TValidationError | null => {
  if (element.type !== TSurveyElementTypeEnum.MultipleChoiceMulti || !Array.isArray(value)) {
    return null;
  }

  const hasOtherOption = "choices" in element && element.choices.some((choice) => choice.id === "other");
  if (!hasOtherOption) {
    return null;
  }

  const sentinelIndex = value.indexOf("");
  if (sentinelIndex === -1) {
    return null;
  }

  const otherText = value[sentinelIndex + 1];
  if (typeof otherText !== "string" || otherText.trim() === "") {
    return createRequiredError(t);
  }

  return null;
};

// A ranked "Other" stores the respondent's text in its slot, so an empty entry means it was ranked
// but nothing was typed. Ranking stores no other sentinel, so "" is unambiguous.
const validateRankingOtherValue = (
  element: TSurveyElement,
  value: TResponseDataValue,
  t: TFunction
): TValidationError | null => {
  if (element.type !== TSurveyElementTypeEnum.Ranking || !Array.isArray(value)) {
    return null;
  }

  const hasOtherOption = element.choices.some((choice) => choice.id === "other");
  if (!hasOtherOption) {
    return null;
  }

  if (value.some((entry) => typeof entry === "string" && entry.trim() === "")) {
    return createRequiredError(t);
  }

  return null;
};

const validateSingleSelectOtherValue = (
  element: TSurveyElement,
  value: TResponseDataValue,
  languageCode: string,
  t: TFunction
): TValidationError | null => {
  if (element.type !== TSurveyElementTypeEnum.MultipleChoiceSingle || typeof value !== "string") {
    return null;
  }

  const hasOtherOption = "choices" in element && element.choices.some((choice) => choice.id === "other");
  if (!hasOtherOption || (element.required && value === "")) {
    return null;
  }

  const knownChoiceIds = element.choices.filter((choice) => choice.id !== "other").map((choice) => choice.id);
  if (knownChoiceIds.includes(value)) {
    return null;
  }

  const knownChoiceLabels = element.choices
    .filter((choice) => choice.id !== "other")
    .map((choice) => getLocalizedValue(choice.label, languageCode));
  if (knownChoiceLabels.includes(value)) {
    return null;
  }

  if (value.trim() === "") {
    return createRequiredError(t);
  }

  return null;
};

/**
 * Every value a legitimate client can submit for these choices: each id, plus each label in any of
 * its stored languages. Not just the response's language: the renderer shows the default language
 * through the `default` key but reports the response language as the default's real code, so a stale
 * non-empty value under that code (e.g. left over from a language switch) would otherwise reject the
 * label the respondent actually saw (ENG-4103).
 */
const getKnownChoiceValues = (choices: { id: string; label?: Record<string, unknown> }[]): Set<string> => {
  const knownValues = new Set<string>();
  for (const choice of choices) {
    knownValues.add(choice.id);
    const labels = Object.values(choice.label ?? {}).filter(
      (label): label is string => typeof label === "string" && label !== ""
    );
    labels.forEach((label) => knownValues.add(label));
  }
  return knownValues;
};

/**
 * Reject answer values that are not among a choice element's configured options.
 *
 * Choice elements that expose an "Other" option intentionally accept free text, so this
 * check only applies when the element has NO "Other" option — there a legitimate client can
 * only ever submit a configured choice (by id or localized label), so any other value is
 * tampered/garbage input submitted directly to the API. Empty values are deferred to the
 * required check.
 */
const validateChoiceMembership = (
  element: TSurveyElement,
  value: TResponseDataValue,
  t: TFunction
): TValidationError | null => {
  if (
    element.type !== TSurveyElementTypeEnum.MultipleChoiceSingle &&
    element.type !== TSurveyElementTypeEnum.MultipleChoiceMulti
  ) {
    return null;
  }

  // Defensive: a malformed survey element could be missing `choices` at runtime; match the
  // other choice validators and bail rather than throw.
  if (!("choices" in element) || !Array.isArray(element.choices)) {
    return null;
  }

  const hasOtherOption = element.choices.some((choice) => choice.id === "other");
  if (hasOtherOption || isEmpty(value)) {
    return null;
  }

  const knownValues = getKnownChoiceValues(element.choices);

  const submittedValues = Array.isArray(value) ? value : [value];
  for (const submitted of submittedValues) {
    // Tolerate stray empty/sentinel entries; emptiness is the required check's concern.
    if (submitted === "") {
      continue;
    }
    if (typeof submitted !== "string" || !knownValues.has(submitted)) {
      return createInvalidOptionError(t);
    }
  }

  return null;
};

/**
 * Check required field validation
 */
const checkRequiredField = (
  element: TSurveyElement,
  value: TResponseDataValue,
  t: TFunction
): TValidationError | null => {
  if (!element.required) {
    return null;
  }

  // CTA elements never block progression (informational only)
  if (element.type === TSurveyElementTypeEnum.CTA) {
    return null;
  }

  if (element.type === TSurveyElementTypeEnum.Ranking) {
    return validateRequiredRanking(value, t);
  }

  if (element.type === TSurveyElementTypeEnum.Matrix) {
    return validateRequiredMatrix(value, element, t);
  }

  if (isEmpty(value)) {
    return createRequiredError(t);
  }

  return null;
};

/**
 * Add implicit validation rules for OpenText elements based on inputType
 */
const addImplicitOpenTextRules = (element: TSurveyElement, rules: TValidationRule[]): TValidationRule[] => {
  if (element.type !== TSurveyElementTypeEnum.OpenText || !("inputType" in element)) {
    return rules;
  }

  const inputType = element.inputType;
  const hasRule = (type: string) => rules.some((r) => r.type === type);

  if (inputType === "email" && !hasRule("email")) {
    rules.push({
      id: "__implicit_email__",
      type: "email",
      params: {},
    });
  } else if (inputType === "url" && !hasRule("url")) {
    rules.push({
      id: "__implicit_url__",
      type: "url",
      params: {},
    });
  } else if (inputType === "phone" && !hasRule("phone")) {
    rules.push({
      id: "__implicit_phone__",
      type: "phone",
      params: {},
    });
  }

  return rules;
};

/**
 * Add implicit validation rules for ContactInfo elements
 */
const addImplicitContactInfoRules = (
  element: TSurveyElement,
  rules: TValidationRule[]
): TValidationRule[] => {
  if (element.type !== TSurveyElementTypeEnum.ContactInfo) {
    return rules;
  }

  const contactInfoElement = element;
  const hasFieldRule = (type: string, field: string) =>
    rules.some((r) => r.type === type && r.field === field);

  if (contactInfoElement.email?.show && !hasFieldRule("email", "email")) {
    rules.push({
      id: "__implicit_email_field__",
      type: "email",
      field: "email",
      params: {},
    });
  }

  if (contactInfoElement.phone?.show && !hasFieldRule("phone", "phone")) {
    rules.push({
      id: "__implicit_phone_field__",
      type: "phone",
      field: "phone",
      params: {},
    });
  }

  return rules;
};

/**
 * Get field value for address/contact info elements
 */
const getFieldValue = (
  rule: TValidationRule,
  element: TSurveyElement,
  elementValue: TResponseDataValue
): TResponseDataValue => {
  if (!rule.field) {
    return elementValue;
  }

  if (element.type === TSurveyElementTypeEnum.Address && Array.isArray(elementValue)) {
    const addressFieldOrder: TAddressField[] = [
      "addressLine1",
      "addressLine2",
      "city",
      "state",
      "zip",
      "country",
    ];
    const fieldIndex = addressFieldOrder.indexOf(rule.field as TAddressField);
    if (fieldIndex >= 0 && fieldIndex < elementValue.length) {
      return elementValue[fieldIndex] ?? "";
    }
  }

  if (element.type === TSurveyElementTypeEnum.ContactInfo && Array.isArray(elementValue)) {
    const contactFieldOrder: TContactInfoField[] = ["firstName", "lastName", "email", "phone", "company"];
    const fieldIndex = contactFieldOrder.indexOf(rule.field as TContactInfoField);
    if (fieldIndex >= 0 && fieldIndex < elementValue.length) {
      return elementValue[fieldIndex] ?? "";
    }
  }

  return "";
};

/**
 * Execute validation rules with OR logic
 */
const executeOrLogic = (
  rules: TValidationRule[],
  element: TSurveyElement,
  value: TResponseDataValue,
  languageCode: string,
  initialErrors: TValidationError[],
  t: TFunction,
  options?: TValidationOptions
): TValidationResult => {
  const ruleResults: TValidationError[] = [];

  for (const rule of rules) {
    const validator = validators[rule.type];
    if (!validator) {
      console.warn(`Unknown validation rule type: ${rule.type}`);
      continue;
    }

    const valueToValidate = getFieldValue(rule, element, value);
    const checkResult = validator.check(valueToValidate, rule.params, element, options);

    if (checkResult.valid) {
      return { valid: initialErrors.length === 0, errors: initialErrors };
    }

    const message = getDefaultErrorMessage(rule, element, languageCode, t);
    ruleResults.push({
      ruleId: rule.id,
      ruleType: rule.type,
      message,
    });
  }

  if (ruleResults.length === 0) {
    return { valid: initialErrors.length === 0, errors: initialErrors };
  }

  return { valid: false, errors: [...initialErrors, ...ruleResults] };
};

/**
 * Execute validation rules with AND logic
 */
const executeAndLogic = (
  rules: TValidationRule[],
  element: TSurveyElement,
  value: TResponseDataValue,
  languageCode: string,
  initialErrors: TValidationError[],
  t: TFunction,
  options?: TValidationOptions
): TValidationResult => {
  const errors = [...initialErrors];

  for (const rule of rules) {
    const validator = validators[rule.type];
    if (!validator) {
      console.warn(`Unknown validation rule type: ${rule.type}`);
      continue;
    }

    const valueToValidate = getFieldValue(rule, element, value);
    const checkResult = validator.check(valueToValidate, rule.params, element, options);

    if (!checkResult.valid) {
      const message = getDefaultErrorMessage(rule, element, languageCode, t);
      errors.push({
        ruleId: rule.id,
        ruleType: rule.type,
        message,
      });
    }
  }

  return { valid: errors.length === 0, errors };
};

/**
 * The options, rows and columns the respondent was not offered (ENG-7332): the ones the survey marks
 * Hidden, which are never shown, plus the ones the response's not-shown record lists, which show-if
 * kept from this respondent. The survey hands over an element already filtered this way, so both are
 * empty there; a server holds the survey as stored and needs them.
 */
const getOptionsNotOffered = (
  element: TSurveyElement,
  options: TValidationOptions | undefined
): TElementOptionsNotShown => {
  // With every show-if passing, only Hidden items remain: the record covers the show-if ones.
  const hidden = getElementOptionsNotShown(element, () => true);
  const recorded = getElementOptionsNotShownFromRecord(options?.notShown, element.id);
  const notOffered: TElementOptionsNotShown = {};
  for (const listKey of getOptionListKeys(element.type)) {
    const ids = new Set([...(hidden[listKey] ?? []), ...(recorded[listKey] ?? [])]);
    if (ids.size > 0) notOffered[listKey] = [...ids];
  }
  return notOffered;
};

/** Question types whose answer covers every item they offer: a ranking ranks, a matrix rates each row. */
const RANKS_OR_RATES_EVERY_ITEM: ReadonlySet<string> = new Set([
  TSurveyElementTypeEnum.Ranking,
  TSurveyElementTypeEnum.Matrix,
]);

/**
 * The answer without what it says about options, rows and columns the respondent was not offered. The
 * survey names them by label, which `dropOptionsFromAnswer` removes; an API caller may name them by id,
 * which the choice check accepts too, so ids go as well.
 */
const dropNotOfferedAnswers = (
  element: TSurveyElement,
  notOffered: TElementOptionsNotShown,
  value: TResponseDataValue,
  languageCode: string
): TResponseDataValue => {
  const withoutLabels = dropOptionsFromAnswer(element, notOffered, value, languageCode);
  const choiceIds = new Set(notOffered.choices ?? []);
  const rowIds = new Set(notOffered.rows ?? []);
  const columnIds = new Set(notOffered.columns ?? []);

  if (typeof withoutLabels === "string") return choiceIds.has(withoutLabels) ? "" : withoutLabels;
  if (Array.isArray(withoutLabels)) return withoutLabels.filter((entry) => !choiceIds.has(entry));
  const isMatrixAnswer =
    typeof withoutLabels === "object" && withoutLabels !== null && !Array.isArray(withoutLabels);
  if (element.type === TSurveyElementTypeEnum.Matrix && isMatrixAnswer) {
    return Object.fromEntries(
      Object.entries(withoutLabels).filter(
        ([row, column]) => !rowIds.has(row) && !(typeof column === "string" && columnIds.has(column))
      )
    ) as TResponseDataValue;
  }
  return withoutLabels;
};

/**
 * Single entrypoint for validating an element's response value.
 * Called by block-conditional.tsx during form submission.
 *
 * @param element - The survey element being validated
 * @param value - The response value for this element
 * @param languageCode - Current language code for error messages
 * @param options - Engine overrides; servers pass a linear-time `matchPattern`
 * @returns Validation result with valid flag and array of errors
 */
export const validateElementResponse = (
  element: TSurveyElement,
  value: TResponseDataValue,
  languageCode: string,
  options?: TValidationOptions
): TValidationResult => {
  const errors: TValidationError[] = [];
  // Always create translation function from surveys package's i18n instance
  const t: TFunction = getTranslations(languageCode);

  // Check if element is required (separate from validation rules)
  const requiredError = checkRequiredField(element, value, t);
  if (requiredError) {
    errors.push(requiredError);
  }

  const singleSelectOtherError = validateSingleSelectOtherValue(element, value, languageCode, t);
  if (singleSelectOtherError) {
    errors.push(singleSelectOtherError);
  }

  const multiSelectOtherError = validateMultiSelectOtherValue(element, value, t);
  if (multiSelectOtherError) {
    errors.push(multiSelectOtherError);
  }

  const rankingOtherError = validateRankingOtherValue(element, value, t);
  if (rankingOtherError) {
    errors.push(rankingOtherError);
  }

  const invalidOptionError = validateChoiceMembership(element, value, t);
  if (invalidOptionError) {
    errors.push(invalidOptionError);
  }

  // Validation rules apply to matrix elements regardless of required status

  // Rules read the element and the answer as the respondent was offered them, the way the survey checks
  // them in the browser (ENG-7332): "Answer all rows" counts the rows shown, not the Hidden ones. The
  // checks above keep the full element, so an answer naming a Hidden option is still a known one.
  const notOffered = getOptionsNotOffered(element, options);
  const hasNotOffered = Object.keys(notOffered).length > 0;
  const offeredElement = hasNotOffered ? withOptionsShown(element, notOffered) : element;
  const offeredValue = hasNotOffered
    ? dropNotOfferedAnswers(element, notOffered, value, languageCode)
    : value;

  // A required ranking or matrix must rank or rate something it offers. The required check above reads
  // the full answer, so it runs again on the offered one: an answer naming only what the question does
  // not offer reads as unanswered, where the rules alone would skip it once emptied.
  if (!requiredError && hasNotOffered && RANKS_OR_RATES_EVERY_ITEM.has(element.type)) {
    const offeredRequiredError = checkRequiredField(offeredElement, offeredValue, t);
    if (offeredRequiredError) errors.push(offeredRequiredError);
  }

  // Get validation rules
  const validation = (
    element as TSurveyElement & { validation?: { rules?: TValidationRule[]; logic?: "and" | "or" } }
  ).validation;
  let rules: TValidationRule[] = [...(validation?.rules ?? [])];

  // Add implicit rules based on element type
  rules = addImplicitOpenTextRules(element, rules);
  rules = addImplicitContactInfoRules(element, rules);

  if (rules.length === 0) {
    return { valid: errors.length === 0, errors };
  }

  const validationLogic = validation?.logic ?? "and";

  if (validationLogic === "or") {
    return executeOrLogic(rules, offeredElement, offeredValue, languageCode, errors, t, options);
  }

  return executeAndLogic(rules, offeredElement, offeredValue, languageCode, errors, t, options);
};

/**
 * Validate all elements in a block, returning an error map.
 *
 * @param elements - Array of elements to validate
 * @param responses - Response data keyed by element ID
 * @param languageCode - Current language code for error messages
 * @param options - Engine overrides; servers pass a linear-time `matchPattern`
 * @returns Map of element IDs to their validation errors
 */
export const validateBlockResponses = (
  elements: TSurveyElement[],
  responses: TResponseData,
  languageCode: string,
  options?: TValidationOptions
): TValidationErrorMap => {
  const errorMap: TValidationErrorMap = {};
  for (const element of elements) {
    const result = validateElementResponse(element, responses[element.id], languageCode, options);
    if (!result.valid) {
      errorMap[element.id] = result.errors;
    }
  }

  return errorMap;
};

/**
 * Get the first error message for an element from the error map.
 * Useful for UI components that only display one error at a time.
 *
 * @param errorMap - The validation error map
 * @param elementId - The element ID to get error for
 * @returns The first error message or undefined
 */
export const getFirstErrorMessage = (
  errorMap: TValidationErrorMap,
  elementId: string
): string | undefined => {
  const errors = errorMap[elementId];
  return errors?.[0]?.message;
};
