import { ChatMenuOption, ChatMessageType } from '../../types/chatAssistant';

const FIELD_LABELS: Record<string, string> = {
  id: 'ID',
  name: 'Nombre',
  cif: 'CIF/NIF',
  email: 'Email',
  phone: 'Teléfono',
  address: 'Dirección',
  mobile: 'Móvil',
  landline: 'Fijo',
  street: 'Calle',
  number: 'Número',
  floor: 'Piso',
  postal_code: 'C.P.',
  city: 'Ciudad',
};

export function normalizeChatText(text: string): string {
  let normalized = text;

  if (normalized.includes('\\n') || normalized.includes('\\r') || normalized.includes('\\t')) {
    normalized = normalized
      .replace(/\\r\\n/g, '\n')
      .replace(/\\n/g, '\n')
      .replace(/\\r/g, '\n')
      .replace(/\\t/g, '\t');
  }

  if (/\\u[0-9a-fA-F]{4}/.test(normalized)) {
    try {
      normalized = JSON.parse(`"${normalized.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`) as string;
    } catch {
      return normalized;
    }
  }

  return normalized;
}

export function splitChatTextLines(text: string): string[] {
  return normalizeChatText(text).split(/\r?\n/);
}

export function formatFieldLabel(key: string): string {
  if (FIELD_LABELS[key]) {
    return FIELD_LABELS[key];
  }

  return key
    .replace(/_/g, ' ')
    .replace(/\b\w/g, (character) => character.toUpperCase());
}

export function formatFieldValueAsText(value: unknown): string {
  if (value === null || value === undefined || value === '') {
    return '—';
  }

  if (typeof value === 'string') {
    return normalizeChatText(value);
  }

  if (typeof value === 'number' || typeof value === 'boolean') {
    return String(value);
  }

  if (Array.isArray(value)) {
    return value.map(formatFieldValueAsText).join(', ');
  }

  if (typeof value === 'object') {
    return Object.entries(value as Record<string, unknown>)
      .map(([key, nestedValue]) => `${formatFieldLabel(key)}: ${formatFieldValueAsText(nestedValue)}`)
      .join(' · ');
  }

  return String(value);
}

export function hasNestedValues(data: Record<string, unknown>[]): boolean {
  return data.some((row) =>
    Object.values(row).some(
      (value) => value !== null && typeof value === 'object' && !Array.isArray(value),
    ),
  );
}

export type ChatDataView = 'table' | 'card' | 'menu';

export function resolveChatDataView(
  data: Record<string, unknown>[],
  messageType?: ChatMessageType,
): ChatDataView | null {
  if (data.length === 0) {
    return null;
  }

  if (messageType === 'menu') {
    return 'menu';
  }

  if (messageType === 'table') {
    return 'table';
  }

  if (messageType === 'card') {
    return 'card';
  }

  if (hasNestedValues(data) || data.length === 1) {
    return 'card';
  }

  return 'table';
}

function isMenuOption(row: Record<string, unknown>): row is Record<string, unknown> & ChatMenuOption {
  return (
    typeof row.value === 'string' &&
    row.value.trim() !== '' &&
    (typeof row.label === 'string' || typeof row.value === 'string')
  );
}

export function extractMenuOptions(data: Record<string, unknown>[]): ChatMenuOption[] {
  return data.filter(isMenuOption).map((row, index) => ({
    id: typeof row.id === 'string' && row.id !== '' ? row.id : `option-${index}`,
    label: normalizeChatText(
      typeof row.label === 'string' && row.label.trim() !== '' ? row.label : String(row.value),
    ),
    value: normalizeChatText(String(row.value)),
  }));
}
