import { TFunction } from "i18next";
import type { FeedbackRecordData, FeedbackRecordTaxonomy } from "@/modules/hub/types";
import { SOURCE_TYPE_PRESET_OPTIONS, type TFeedbackRecordFormValues } from "./types";

export interface ResolvedFeedbackText {
  text: string | null; // translation if usable, else original value_text
  original: string | null;
  isTranslated: boolean; // non-empty translation that differs from the original
  langKey: string | null; // set only when isTranslated
}

export const getTaxonomyAssignmentDisplay = (
  taxonomy: FeedbackRecordTaxonomy | null
): { path: string | null; status: FeedbackRecordTaxonomy["status"] | "unavailable" } => {
  if (taxonomy?.status === "classified" && taxonomy.path.length > 0) {
    return { path: taxonomy.path.map((node) => node.label).join(" › "), status: "classified" };
  }

  if (taxonomy?.status === "no_active_taxonomy") {
    return { path: null, status: "no_active_taxonomy" };
  }

  if (taxonomy?.status === "unclassified") {
    return { path: null, status: "unclassified" };
  }

  return { path: null, status: "unavailable" };
};

// Pick which feedback text to show (ENG-1253): the translation when usable, else the original.
export const resolveFeedbackDisplayText = (
  record: Pick<FeedbackRecordData, "value_text" | "value_text_translated" | "translation_lang_key">
): ResolvedFeedbackText => {
  const original = record.value_text ?? null;
  const translated = record.value_text_translated;
  const hasTranslation =
    typeof translated === "string" && translated.trim().length > 0 && translated !== original;

  return {
    text: hasTranslation ? translated : original,
    original,
    isTranslated: hasTranslation,
    langKey: hasTranslation ? (record.translation_lang_key ?? null) : null,
  };
};

export const getValueFieldByType = (
  fieldType: TFeedbackRecordFormValues["field_type"]
): "value_text" | "value_number" | "value_boolean" | "value_date" => {
  switch (fieldType) {
    case "boolean":
      return "value_boolean";
    case "date":
      return "value_date";
    case "nps":
    case "csat":
    case "ces":
    case "rating":
    case "number":
      return "value_number";
    default:
      return "value_text";
  }
};

export const toLocalDateTimeInput = (isoDate: string): string => {
  const date = new Date(isoDate);
  if (!Number.isFinite(date.getTime())) {
    return "";
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  return `${year}-${month}-${day}T${hours}:${minutes}`;
};

export const toISOOrUndefined = (dateTimeValue: string | undefined): string | undefined => {
  if (!dateTimeValue) {
    return undefined;
  }

  const parsed = new Date(dateTimeValue);
  if (!Number.isFinite(parsed.getTime())) {
    return undefined;
  }

  return parsed.toISOString();
};

export const mapRecordToValues = (record: FeedbackRecordData): TFeedbackRecordFormValues => {
  return {
    id: record.id,
    tenant_id: record.tenant_id,
    submission_id: record.submission_id,
    collected_at: toLocalDateTimeInput(record.collected_at),
    created_at: record.created_at ? toLocalDateTimeInput(record.created_at) : "",
    updated_at: record.updated_at ? toLocalDateTimeInput(record.updated_at) : "",
    source_type: record.source_type,
    source_id: record.source_id ?? "",
    source_name: record.source_name ?? "",
    field_id: record.field_id,
    field_label: record.field_label ?? "",
    field_type: record.field_type,
    field_group_id: record.field_group_id ?? "",
    field_group_label: record.field_group_label ?? "",
    value_text: record.value_text ?? "",
    value_number: record.value_number == null ? "" : String(record.value_number),
    value_boolean: record.value_boolean,
    value_date: record.value_date ? toLocalDateTimeInput(record.value_date) : "",
    language: record.language ?? "",
    user_id: record.user_id ?? "",
  };
};

/** Where the survey pipeline publishes a response's Embedded Data on each record (ENG-3290). */
const EMBEDDED_DATA_METADATA_KEY = "embedded_data";

const isPlainObject = (value: unknown): value is Record<string, unknown> =>
  typeof value === "object" && value !== null && !Array.isArray(value);

/**
 * Every metadata entry, for the drawer's read-only list, except an `embedded_data` object:
 * `getEmbeddedDataEntries` gives that one its own rows. Strings are shown as-is; anything else is
 * JSON, so a boolean or an object still reads unambiguously.
 */
export const getReadOnlyMetadataEntries = (record: FeedbackRecordData): { key: string; value: string }[] => {
  return Object.entries(record.metadata ?? {})
    .filter(([key, value]) => !(key === EMBEDDED_DATA_METADATA_KEY && isPlainObject(value)))
    .map(([key, value]) => ({
      key,
      value: typeof value === "string" ? value : JSON.stringify(value),
    }));
};

/**
 * The record's Embedded Data as one row per field, sorted by name.
 *
 * Only a real object counts: `metadata` is free-form, and the public API, CSV import and MCP can put
 * anything under this key. Anything else stays in the generic metadata list, so it is never hidden.
 * Sorted because Hub stores `metadata` as jsonb, which reorders keys by length rather than keeping
 * the order the survey declared them in.
 */
export const getEmbeddedDataEntries = (record: FeedbackRecordData): { key: string; value: string }[] => {
  // `metadata` reads back as whatever JSON was written, so a legacy record can hold an array or a scalar.
  const embeddedData = isPlainObject(record.metadata)
    ? record.metadata[EMBEDDED_DATA_METADATA_KEY]
    : undefined;
  if (!isPlainObject(embeddedData)) return [];

  return Object.entries(embeddedData)
    .map(([key, value]) => ({ key, value: typeof value === "string" ? value : JSON.stringify(value) }))
    .sort((a, b) => a.key.localeCompare(b.key));
};

export const parseNumberValue = (value: string): number | null => {
  if (value.trim() === "") return null;
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : null;
};

export const isPresetSourceType = (value: string): value is (typeof SOURCE_TYPE_PRESET_OPTIONS)[number] =>
  (SOURCE_TYPE_PRESET_OPTIONS as readonly string[]).includes(value);

// Field types that are acronyms and should render fully upper-cased (e.g. "nps" -> "NPS").
const FIELD_TYPE_ACRONYMS = new Set(["nps", "csat", "ces"]);

// Human-readable field type: acronyms upper-cased, everything else capitalized ("text" -> "Text").
export const formatFieldType = (fieldType: string): string => {
  if (!fieldType) return fieldType;
  if (FIELD_TYPE_ACRONYMS.has(fieldType)) return fieldType.toUpperCase();
  return fieldType.charAt(0).toUpperCase() + fieldType.slice(1);
};

/**
 * Translated field-type name, for places where the type is read rather than shown as an icon.
 *
 * Unlike `formatFieldType`, which just re-cases the stored machine value, this is the user-facing
 * spelling — so it is what belongs in an `aria-label`, where the icon has no other text to stand in
 * for it. Falls back to the re-cased raw value for a type the map does not know yet.
 */
export const formatFieldTypeLabel = (fieldType: string, t: TFunction): string => {
  switch (fieldType) {
    case "text":
      return t("workspace.unify.field_type_label_text");
    case "categorical":
      return t("workspace.unify.field_type_label_categorical");
    case "nps":
      return t("workspace.unify.field_type_label_nps");
    case "csat":
      return t("workspace.unify.field_type_label_csat");
    case "ces":
      return t("workspace.unify.field_type_label_ces");
    case "rating":
      return t("workspace.unify.field_type_label_rating");
    case "number":
      return t("workspace.unify.field_type_label_number");
    case "boolean":
      return t("workspace.unify.field_type_label_boolean");
    case "date":
      return t("workspace.unify.field_type_label_date");
    default:
      return formatFieldType(fieldType);
  }
};

export const formatSourceType = (sourceType: string, t: TFunction): string => {
  switch (sourceType) {
    case "formbricks":
    case "formbricks_survey":
      return t("workspace.unify.formbricks_surveys");
    case "csv":
      return t("workspace.unify.csv_import");
    case "survey":
      return t("workspace.unify.source_type_label_survey");
    case "review":
      return t("workspace.unify.source_type_label_review");
    case "feedback_form":
      return t("workspace.unify.source_type_label_feedback_form");
    case "support":
      return t("workspace.unify.source_type_label_support");
    case "social":
      return t("workspace.unify.source_type_label_social");
    case "interview":
      return t("workspace.unify.source_type_label_interview");
    case "usability_test":
      return t("workspace.unify.source_type_label_usability_test");
    case "nps_campaign":
      return t("workspace.unify.source_type_label_nps_campaign");
    default:
      return sourceType;
  }
};
