import { TFunction } from "i18next";
import { toast } from "react-hot-toast";
import {
  TFeedbackSourceType,
  TFeedbackSourceWithMappings,
  THubFieldType,
  UNSUPPORTED_FEEDBACK_SOURCE_ELEMENT_TYPES,
  ZHubFieldType,
} from "@formbricks/types/feedback-source";
import {
  CSV_REQUIRED_UI_FIELDS,
  CSV_TARGET_FIELDS,
  FEEDBACK_RECORD_FIELDS,
  MAX_CSV_VALUES,
  TFieldMapping,
  TSourceField,
  TUnifySurvey,
} from "./types";

export const getDismissedStorageKey = (workspaceId: string) => `${workspaceId}-dismissedFeedbackSuggestions`;

/**
 * Surveys to surface as import suggestions below the connected sources.
 * Excludes surveys already backing a source, and drafts — a draft has never collected responses,
 * so suggesting it for import would only offer an empty source.
 */
export const getSuggestedSurveys = (
  surveys: TUnifySurvey[],
  connectedSurveyIds: string[]
): TUnifySurvey[] => {
  const connectedSurveyIdSet = new Set(connectedSurveyIds);
  return surveys.filter((survey) => !connectedSurveyIdSet.has(survey.id) && survey.status !== "draft");
};

/** Survey element ids that can be mapped to a feedback source (drops unsupported question types). */
export const getSelectableQuestionIds = (survey: TUnifySurvey): string[] =>
  survey.elements
    .filter(
      (element) => !(UNSUPPORTED_FEEDBACK_SOURCE_ELEMENT_TYPES as readonly string[]).includes(element.type)
    )
    .map((element) => element.id);

/**
 * Distinct surveys a Formbricks source replays responses from.
 *
 * `formbricksMappings` holds one row per mapped question, so a source covering five questions has
 * five rows all naming the same survey — hence the dedupe. It reads every distinct survey rather
 * than assuming the first because the schema does not forbid more than one:
 * `@@unique([workspaceId, feedbackSourceId, surveyId, elementId])`. Today's create dialog only
 * ever binds one survey, so this normally returns a single id; taking `[0]` instead would turn a
 * future multi-survey source into a silent partial re-import.
 */
export const getMappedSurveyIds = (feedbackSource: TFeedbackSourceWithMappings): string[] => [
  ...new Set(feedbackSource.formbricksMappings.map((mapping) => mapping.surveyId)),
];

/**
 * Whether "Re-import historic data" applies to a source.
 *
 * Only Formbricks sources replay responses (`importHistoricalResponses` rejects every other type),
 * and only one that names a survey has anything to replay from.
 *
 * `status` is part of the gate because pausing a source is the user's switch for stopping it
 * writing into its feedback directory — the live pipeline honours it (`getFeedbackSourcesBySurveyId`
 * filters `status: "active"`). Neither the action nor the import re-checks status, so without this
 * the menu would offer to replay a whole response history into a directory the user had just
 * paused the source to keep out of. Create-time import could never reach that case: a source is
 * active the moment it is created.
 */
export const canReimportHistoricalData = (feedbackSource: TFeedbackSourceWithMappings): boolean =>
  feedbackSource.type === "formbricks_survey" &&
  feedbackSource.status === "active" &&
  getMappedSurveyIds(feedbackSource).length > 0;

/**
 * Counts from a historical import. Structurally identical to `TImportResult` in
 * `lib/feedback-source/import.ts`, redeclared here because that module is `server-only` and this
 * one is reached from client components.
 */
export interface TFeedbackImportTotals {
  successes: number;
  failures: number;
  skipped: number;
}

/** One set of totals for a source, however many surveys it replayed. */
export const sumImportTotals = (totals: TFeedbackImportTotals[]): TFeedbackImportTotals =>
  totals.reduce<TFeedbackImportTotals>(
    (acc, next) => ({
      successes: acc.successes + next.successes,
      failures: acc.failures + next.failures,
      skipped: acc.skipped + next.skipped,
    }),
    { successes: 0, failures: 0, skipped: 0 }
  );

/**
 * Announce an import's totals, picking the toast by `failures` rather than by whether the action
 * resolved.
 *
 * A failed import does not throw: `reconcileFeedbackRecords` folds per-record errors into
 * `failures` and the action resolves normally, so a Hub outage returns `{ successes: 0,
 * failures: N }`. Reporting that as a green toast made a run that wrote nothing look identical to
 * the happy path.
 *
 * `showSuccess` is how the create modal keeps its "Feedback records" link on the success toast —
 * a green toast inviting the user to go and look at records that were never written is the sharper
 * half of the same bug. Every import site passes the same `message` it would have shown anyway,
 * so the CSV and historical wordings stay distinct.
 */
export const notifyImportResult = (
  totals: TFeedbackImportTotals,
  message: string,
  showSuccess: (message: string) => void = toast.success
): boolean => {
  if (totals.failures > 0) {
    toast.error(message);
    return false;
  }

  showSuccess(message);
  return true;
};

export type TFeedbackSourceOptionId = TFeedbackSourceType | "api_ingestion" | "feedback_record_mcp";

export interface TFeedbackSourceOption {
  id: TFeedbackSourceOptionId;
  name: string;
  description: string;
}

export const getFeedbackSourceOptions = (t: TFunction): TFeedbackSourceOption[] => [
  {
    id: "formbricks_survey",
    name: t("workspace.unify.formbricks_surveys"),
    description: t("workspace.unify.source_connect_formbricks_description"),
  },
  {
    id: "csv",
    name: t("workspace.unify.csv_import"),
    description: t("workspace.unify.source_connect_csv_description"),
  },
  {
    id: "api_ingestion",
    name: t("workspace.unify.api_ingestion"),
    description: t("workspace.unify.api_ingestion_settings_description"),
  },
  {
    id: "feedback_record_mcp",
    name: t("workspace.unify.feedback_record_mcp"),
    description: t("workspace.unify.source_connect_feedback_record_mcp_description"),
  },
];

export const parseCSVColumnsToFields = (
  columns: string,
  { includeSampleValues = true }: { includeSampleValues?: boolean } = {}
): TSourceField[] => {
  return columns.split(",").map((col) => {
    const trimmed = col.trim();
    return {
      id: trimmed,
      name: trimmed,
      type: "string",
      sampleValue: includeSampleValues ? `Sample ${trimmed}` : undefined,
    };
  });
};

export interface TEnumValidationError {
  targetFieldName: string;
  invalidEntries: { row: number; value: string }[];
  allowedValues: string[];
}

export const validateEnumMappings = (
  mappings: TFieldMapping[],
  csvData: Record<string, string>[]
): TEnumValidationError[] => {
  const errors: TEnumValidationError[] = [];

  for (const mapping of mappings) {
    if (!mapping.sourceFieldId || mapping.staticValue) continue;

    const targetField = FEEDBACK_RECORD_FIELDS.find((f) => f.id === mapping.targetFieldId);
    if (targetField?.type !== "enum" || !targetField?.enumValues) continue;

    const allowedValues = new Set(targetField.enumValues);
    const invalidEntries: { row: number; value: string }[] = [];

    for (let i = 0; i < csvData.length; i++) {
      const value = csvData[i][mapping.sourceFieldId]?.trim();
      if (value && !allowedValues.has(value as THubFieldType)) {
        invalidEntries.push({ row: i + 1, value });
      }
    }

    if (invalidEntries.length > 0) {
      errors.push({
        targetFieldName: targetField.name,
        invalidEntries,
        allowedValues: targetField.enumValues,
      });
    }
  }

  return errors;
};

export const isFeedbackSourceNameValid = (name: string): boolean => name.trim().length > 0;

export const toggleQuestionId = (currentSelection: string[], questionId: string): string[] => {
  return currentSelection.includes(questionId)
    ? currentSelection.filter((id) => id !== questionId)
    : [...currentSelection, questionId];
};

export const validateCsvFile = (
  file: File,
  t: TFunction
): { valid: true } | { valid: false; error: string } => {
  if (!file.name.endsWith(".csv")) {
    return { valid: false, error: t("workspace.unify.csv_files_only") };
  }
  if (file.type && file.type !== "text/csv" && !file.type.includes("csv")) {
    return { valid: false, error: t("workspace.unify.csv_files_only") };
  }
  if (file.size > MAX_CSV_VALUES.FILE_SIZE) {
    return { valid: false, error: t("workspace.unify.csv_file_too_large") };
  }
  return { valid: true };
};

export type TMappingConfidence = "high" | "medium" | "low";

export const titleizeFromFileName = (fileName: string): string => {
  const base = fileName.replace(/\.csv$/i, "");
  const words = base.split(/[_\-\s]+/).filter(Boolean);
  if (words.length === 0) return base;
  return words.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(" ");
};

export const CSV_COLUMN_ALIASES: Record<string, { high: RegExp[]; medium: RegExp[] }> = {
  collected_at: {
    high: [/^(timestamp|collected_at|submitted_at)$/i],
    medium: [/^(created_at|date|time|datetime)$/i],
  },
  field_id: {
    high: [/^(field_id|question_id|q_id)$/i],
    medium: [/^(id|key)$/i],
  },
  field_type: {
    high: [/^(field_type|type)$/i],
    medium: [],
  },
  field_label: {
    high: [/^(field_label|question|label|question_text)$/i],
    medium: [/^(name|title|prompt)$/i],
  },
  response_value: {
    high: [/^(response|answer|value|response_value)$/i],
    medium: [/^(score|rating|feedback)$/i],
  },
  source_id: {
    high: [/^(source_id|survey_id|form_id)$/i],
    medium: [],
  },
  submission_id: {
    high: [
      /^(submission_id|submissionid|response_id|responseid|record_id|recordid|ticket_id|ticketid|order_id|orderid|request_id|requestid|case_id|caseid)$/i,
    ],
    medium: [/^(submission|record|ticket|order|request|case)$/i],
  },
  language: {
    high: [/^(language|lang|locale)$/i],
    medium: [],
  },
  user_id: {
    high: [/^(user_id|user_identifier|customer_id)$/i],
    medium: [/^(email|user|customer)$/i],
  },
  metadata: {
    high: [/^metadata$/i],
    medium: [],
  },
};

export const FIELD_TYPE_NAME_HINTS: Array<{ pattern: RegExp; type: THubFieldType }> = [
  { pattern: /^(rating|stars|score)$/i, type: "rating" },
  { pattern: /^(nps|nps_score|net_promoter)$/i, type: "nps" },
  { pattern: /^csat$/i, type: "csat" },
  { pattern: /^ces$/i, type: "ces" },
  { pattern: /^(number|count|amount|qty|quantity)$/i, type: "number" },
  { pattern: /^(comment|feedback|answer|response|text)$/i, type: "text" },
  { pattern: /^(category|choice|option|select)$/i, type: "categorical" },
  { pattern: /^(is_|has_|did_)/i, type: "boolean" },
  { pattern: /^(date|submitted_at|completed_at)$/i, type: "date" },
];

export const inferFieldType = ({
  columnName,
  samples,
}: {
  columnName?: string;
  samples: string[];
}): THubFieldType => {
  if (columnName) {
    for (const hint of FIELD_TYPE_NAME_HINTS) {
      if (hint.pattern.test(columnName)) return hint.type;
    }
  }

  const cleaned = samples.map((s) => s?.trim()).filter((s): s is string => Boolean(s));
  if (cleaned.length === 0) return "text";

  const isBool = cleaned.every((s) => /^(true|false|yes|no|0|1)$/i.test(s));
  if (isBool) return "boolean";

  const isNumber = cleaned.every((s) => !Number.isNaN(Number.parseFloat(s)) && /^-?\d+(\.\d+)?$/.test(s));
  if (isNumber) return "number";

  const isDate = cleaned.every((s) => !Number.isNaN(new Date(s).getTime()));
  if (isDate) return "date";

  return "text";
};

interface TAutoMapResult {
  mappings: TFieldMapping[];
  confidence: Record<string, TMappingConfidence>;
}

interface TAutoMapInput {
  sourceFields: TSourceField[];
  sampleRow: Record<string, string>;
  fileName: string;
}

/** What the auto-mapper has decided so far, shared by its steps. */
interface TAutoMapState {
  mappings: TFieldMapping[];
  confidence: Record<string, TMappingConfidence>;
  claimedSources: Set<string>;
  mappableFields: TSourceField[];
}

/** Maps a target to the first unclaimed column one of its aliases at `level` names, if any. */
const mapTargetByAliases = (
  targetId: (typeof CSV_TARGET_FIELDS)[number]["id"],
  level: "high" | "medium",
  { mappings, confidence, claimedSources, mappableFields }: TAutoMapState
): void => {
  const aliases = CSV_COLUMN_ALIASES[targetId];
  if (!aliases) return;
  for (const pattern of aliases[level]) {
    const match = mappableFields.find((f) => !claimedSources.has(f.id) && pattern.test(f.name));
    if (match) {
      mappings.push({ targetFieldId: targetId, sourceFieldId: match.id });
      confidence[targetId] = level;
      claimedSources.add(match.id);
      return;
    }
  }
};

/** A field type inferred from the response column's name and sample, when a column is mapped to it. */
const mapInferredFieldType = (
  { mappings, confidence }: TAutoMapState,
  sourceFields: TSourceField[],
  sampleRow: Record<string, string>
): void => {
  const responseMapping = mappings.find((m) => m.targetFieldId === "response_value");
  if (!responseMapping?.sourceFieldId) return;
  const sourceField = sourceFields.find((f) => f.id === responseMapping.sourceFieldId);
  const inferred = inferFieldType({
    columnName: sourceField?.name,
    samples: [sampleRow[responseMapping.sourceFieldId] ?? ""],
  });
  mappings.push({ targetFieldId: "field_type", staticValue: inferred });
  const nameHinted = sourceField?.name
    ? FIELD_TYPE_NAME_HINTS.some((h) => h.pattern.test(sourceField.name))
    : false;
  confidence.field_type = nameHinted ? "high" : "medium";
};

export const autoMapCsvSourceFields = ({
  sourceFields,
  sampleRow,
  fileName,
}: TAutoMapInput): TAutoMapResult => {
  const mappings: TFieldMapping[] = [];
  const confidence: Record<string, TMappingConfidence> = {};
  const claimedSources = new Set<string>();

  const orderedTargets = CSV_TARGET_FIELDS.map((t) => t.id);

  // Binding a target to a column that has no data makes every row fail the transform (e.g. an
  // empty "Zone ID" column auto-mapped to the required submission_id skips the whole import).
  // Only auto-map columns that actually carry a value in the sample row; otherwise leave the
  // target unmapped so the required-fields check forces an explicit, data-bearing choice.
  const mappableFields = sourceFields.filter((f) => (sampleRow[f.id] ?? "").trim() !== "");

  const state: TAutoMapState = { mappings, confidence, claimedSources, mappableFields };
  for (const targetId of orderedTargets) {
    mapTargetByAliases(targetId, "high", state);
  }

  for (const targetId of orderedTargets) {
    if (confidence[targetId]) continue;
    mapTargetByAliases(targetId, "medium", state);
  }

  if (!confidence.collected_at) {
    mappings.push({ targetFieldId: "collected_at", staticValue: "$now" });
    confidence.collected_at = "high";
  }

  mappings.push({ targetFieldId: "source_name", staticValue: titleizeFromFileName(fileName) });
  confidence.source_name = "high";

  if (!confidence.field_id) {
    const labelMapping = mappings.find((m) => m.targetFieldId === "field_label" && m.sourceFieldId);
    if (labelMapping?.sourceFieldId) {
      mappings.push({ targetFieldId: "field_id", sourceFieldId: labelMapping.sourceFieldId });
      confidence.field_id = "low";
    }
  }

  if (!confidence.field_type) {
    mapInferredFieldType(state, sourceFields, sampleRow);
  }

  return { mappings, confidence };
};

export const isCsvUserDefinedStaticValueMapping = (mapping: TFieldMapping | undefined | null): boolean =>
  Boolean(mapping?.staticValue?.trim() && mapping.staticValue !== "$now");

export type TCsvIdentityMappingAlert =
  | { type: "both_fixed" }
  | { type: "single_fixed"; field: "submission_id" | "field_id" };

export const getCsvIdentityMappingAlert = (mappings: TFieldMapping[]): TCsvIdentityMappingAlert | null => {
  const submissionIdFixed = isCsvUserDefinedStaticValueMapping(
    mappings.find((mapping) => mapping.targetFieldId === "submission_id")
  );
  const fieldIdFixed = isCsvUserDefinedStaticValueMapping(
    mappings.find((mapping) => mapping.targetFieldId === "field_id")
  );

  if (submissionIdFixed && fieldIdFixed) {
    return { type: "both_fixed" };
  }

  if (submissionIdFixed) {
    return { type: "single_fixed", field: "submission_id" };
  }

  if (fieldIdFixed) {
    return { type: "single_fixed", field: "field_id" };
  }

  return null;
};

export const areAllRequiredCsvFieldsMapped = (
  mappings: TFieldMapping[]
): { valid: boolean; missing: string[] } => {
  const missing: string[] = [];
  for (const requiredId of CSV_REQUIRED_UI_FIELDS) {
    const mapping = mappings.find((m) => m.targetFieldId === requiredId);
    const resolved = Boolean(mapping?.sourceFieldId || mapping?.staticValue?.trim());
    if (!resolved) {
      missing.push(requiredId);
      continue;
    }

    if (
      requiredId === "field_type" &&
      mapping?.staticValue &&
      !ZHubFieldType.safeParse(mapping.staticValue).success
    ) {
      missing.push(requiredId);
    }
  }
  return { valid: missing.length === 0, missing };
};
