/**
 * Display & Presentation Helpers
 *
 * Functions for display names, icon mappings, app service information,
 * and config summaries used for node branding in the flow builder.
 *
 * Action/trigger types use namespaced format: "{package-slug}/{type}"
 * e.g. "wordpress/create_update_post", "woocommerce/create_order"
 */

/**
 * Extract the short slug (part after /) from a namespaced type.
 * Returns the full string if no namespace separator is present.
 */
function getShortSlug(type: string): string {
  const slashIndex = type.indexOf('/');
  return slashIndex > -1 ? type.substring(slashIndex + 1) : type;
}

/**
 * Convert a snake_case slug to Title Case display name.
 * e.g. "create_update_post" → "Create Update Post"
 */
function snakeToTitle(slug: string): string {
  return slug
    .split('_')
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}

/**
 * Maps action type to display name.
 * Derives from the short slug portion of the namespaced type.
 */
export function getActionDisplayName(actionType: string): string {
  const slug = getShortSlug(actionType);
  return snakeToTitle(slug);
}

/**
 * Maps trigger type to display name.
 * Derives from the short slug portion of the namespaced type.
 */
export function getTriggerDisplayName(triggerType: string): string {
  const slug = getShortSlug(triggerType);
  return snakeToTitle(slug);
}

/**
 * Maps integration identifier to display name.
 */
export function getAppNameFromIntegration(integration: string): string {
  const integrationNames: Record<string, string> = {
    wordpress: 'WordPress',
    campaignmonitor: 'Campaign Monitor',
    mailchimp: 'Mailchimp',
    slack: 'Slack',
    hubspot: 'HubSpot',
    kit: 'Kit',
    woocommerce: 'WooCommerce',
    airtable: 'Airtable',
    notion: 'Notion',
    gravity_forms: 'Gravity Forms',
  };
  return (
    integrationNames[integration.toLowerCase()] ||
    integration.charAt(0).toUpperCase() + integration.slice(1)
  );
}

/**
 * Derive integration slug from a namespaced type.
 * e.g. "woocommerce/create_order" → "woocommerce"
 * Falls back to "wordpress" for un-namespaced types.
 */
export function deriveIntegrationFromType(type: string): string {
  const slashIndex = type.indexOf('/');
  return slashIndex > -1 ? type.substring(0, slashIndex) : 'wordpress';
}

/**
 * Integration metadata lookup.
 */
const INTEGRATION_INFO: Record<string, { appName: string; appService: string }> = {
  wordpress: { appName: 'WordPress', appService: 'wordpress' },
  woocommerce: { appName: 'WooCommerce', appService: 'woocommerce' },
  campaignmonitor: { appName: 'Campaign Monitor', appService: 'campaignmonitor' },
  mailchimp: { appName: 'Mailchimp', appService: 'mailchimp' },
  slack: { appName: 'Slack', appService: 'slack' },
  hubspot: { appName: 'HubSpot', appService: 'hubspot' },
  kit: { appName: 'Kit', appService: 'kit' },
  airtable: { appName: 'Airtable', appService: 'airtable' },
  notion: { appName: 'Notion', appService: 'notion' },
  gravity_forms: { appName: 'Gravity Forms', appService: 'gravity_forms' },
};

/**
 * Maps action/trigger type to app service info.
 * Returns { appName, appService } for node branding.
 */
export function getAppServiceInfo(actionType: string): { appName: string; appService: string } {
  const integration = deriveIntegrationFromType(actionType);
  return (
    INTEGRATION_INFO[integration] || {
      appName: getAppNameFromIntegration(integration),
      appService: integration,
    }
  );
}

/**
 * Get app info from action/trigger type, considering saved integration.
 */
export function getAppInfo(
  type: string,
  savedIntegration?: string,
): { appName: string; appService: string } {
  // Use saved integration if available.
  if (savedIntegration) {
    return {
      appName: getAppNameFromIntegration(savedIntegration),
      appService: savedIntegration,
    };
  }

  return getAppServiceInfo(type);
}

/**
 * Maps action type to Lucide icon name.
 * Uses keyword matching on the short slug.
 */
export function getActionIconName(actionType: string): string {
  const slug = getShortSlug(actionType);
  if (slug.includes('email') || slug.includes('mail')) return 'Mail';
  if (slug.includes('create') && slug.includes('post')) return 'FilePlus';
  if (slug.includes('update') && slug.includes('post')) return 'FilePenLine';
  if (slug.includes('post')) return 'FileText';
  if (slug.includes('create') && slug.includes('user')) return 'UserPlus';
  if (slug.includes('update') && slug.includes('user')) return 'Pencil';
  if (slug.includes('user')) return 'UserPlus';
  if (slug.includes('order')) return 'ShoppingCart';
  if (slug.includes('product')) return 'Package';
  if (slug.includes('subscriber')) return 'UserPlus';
  if (slug.includes('unsubscribe')) return 'UserMinus';
  if (slug.includes('message')) return 'MessageSquare';
  if (slug.includes('channel')) return 'Hash';
  if (slug.includes('contact')) return 'Contact';
  return 'Zap';
}

/**
 * Maps trigger type to Lucide icon name.
 * Uses keyword matching on the short slug.
 */
export function getTriggerIconName(triggerType: string): string {
  const slug = getShortSlug(triggerType);
  if (slug.includes('registration') || slug.includes('new_customer')) return 'UserPlus';
  if (slug.includes('profile_update')) return 'Pencil';
  if (slug.includes('role_change')) return 'UserCog';
  if (slug.includes('published')) return 'FileCheck';
  if (slug.includes('comment')) return 'MessageSquare';
  if (slug.includes('order')) return 'ShoppingCart';
  if (slug.includes('product') || slug.includes('stock')) return 'Package';
  if (slug.includes('customer')) return 'UserPlus';
  return 'Zap';
}

/**
 * Generates a brief config summary for display on node cards.
 * Extracts the most meaningful configuration value based on action type.
 */
export function getConfigSummary(
  config: Record<string, unknown>,
  actionType: string,
): string | undefined {
  if (!config || Object.keys(config).length === 0) return undefined;

  const slug = getShortSlug(actionType);

  // Email actions - show recipient
  if (slug.includes('email') || slug.includes('mail')) {
    if (config.to) return `To: ${config.to}`;
    if (config.email) return `To: ${config.email}`;
    if (config.recipient) return `To: ${config.recipient}`;
  }

  // Status updates - show status value
  if (slug.includes('status') || slug.includes('update')) {
    if (config.status) return `Status → ${config.status}`;
    if (config.new_status) return `Status → ${config.new_status}`;
  }

  // Subscriber actions - show list or email
  if (slug.includes('subscriber') || slug.includes('contact')) {
    if (config.list_id) return `List: ${config.list_id}`;
    if (config.list) return `List: ${config.list}`;
    if (config.email) return `Email: ${config.email}`;
  }

  // Message/channel actions
  if (slug.includes('message') || slug.includes('channel')) {
    if (config.channel) return `Channel: ${config.channel}`;
  }

  // Post/content actions
  if (slug.includes('post')) {
    if (config.post_type) return `Type: ${config.post_type}`;
    if (config.title) return `Title: ${String(config.title).substring(0, 30)}...`;
  }

  // User actions
  if (slug.includes('user')) {
    if (config.role) return `Role: ${config.role}`;
  }

  // Generic fallback - show first meaningful config key
  const meaningfulKeys = ['name', 'title', 'subject', 'message', 'value', 'target'];
  for (const key of meaningfulKeys) {
    if (config[key] && typeof config[key] === 'string') {
      const value = String(config[key]);
      return `${key}: ${value.length > 25 ? value.substring(0, 25) + '...' : value}`;
    }
  }

  return undefined;
}
