'use client';

import { Loader2 } from 'lucide-react';
import {
  WhatsAppTemplate,
  getHeaderText,
  getFooterText,
} from '@client/api/whatsapp-templates';

/** Fill {{N}} placeholders in the BODY text with stored variable values. */
export function fillBodyText(template: WhatsAppTemplate, vars: string[]): string {
  const body = template.components.find((c) => c.type === 'BODY');
  if (!body?.text) return '';
  return body.text.replace(/\{\{(\d+)\}\}/g, (_match, num: string) => {
    const idx = parseInt(num, 10) - 1;
    return vars[idx] !== undefined && vars[idx] !== '' ? vars[idx] : `{{${num}}}`;
  });
}

interface WhatsAppTemplateBubbleProps {
  /**
   * Resolved template:
   *  - `null`  → still loading
   *  - `false` → fetched but not in cache
   *  - `WhatsAppTemplate` → found; render the green bubble
   */
  template: WhatsAppTemplate | null | false;
  /** Variable values to substitute into {{N}} placeholders. */
  vars: string[];
  /** Template name shown in the fallback view (when template is null or false). */
  templateName?: string | null;
  /** ISO language code shown alongside templateName in the fallback view. */
  templateLang?: string | null;
  /** Translation helper. */
  t: (key: string, fallback?: string) => string;
  /**
   * Text shown next to the spinner while template === null.
   * When omitted the loading state renders the same name fallback as the
   * not-in-cache state (without the amber "not in cache" note).
   */
  loadingText?: string;
}

export function WhatsAppTemplateBubble({
  template,
  vars,
  templateName,
  templateLang,
  t,
  loadingText,
}: WhatsAppTemplateBubbleProps) {
  if (template) {
    return (
      <div className="bg-[#e9fdd8] rounded-lg p-3 text-sm text-gray-800 max-w-sm whitespace-pre-wrap break-words shadow-sm">
        {getHeaderText(template) && (
          <div className="font-semibold mb-1 text-gray-900">{getHeaderText(template)}</div>
        )}
        <div>{fillBodyText(template, vars)}</div>
        {getFooterText(template) && (
          <div className="mt-1 text-xs text-gray-500">{getFooterText(template)}</div>
        )}
      </div>
    );
  }

  if (template === null && loadingText) {
    return (
      <div className="flex items-center gap-1.5 text-xs text-gray-400">
        <Loader2 size={12} className="animate-spin" />
        {loadingText}
      </div>
    );
  }

  return (
    <div className="text-sm text-gray-500 italic">
      {templateName && (
        <span className="font-mono text-gray-700 not-italic">{templateName}</span>
      )}
      {templateLang && (
        <span className="ml-1 text-xs text-gray-400">({templateLang})</span>
      )}
      {template === false && (
        <span className="ml-2 text-xs text-amber-600">
          {t('marketing.report.templateNotCached', '— template no longer in cache')}
        </span>
      )}
    </div>
  );
}
