import { ExternalLink, FileAudio, FileText, FileVideo, List, Reply } from "lucide-react";
import type { BotAsset, InteractiveContent, MediaContent, ReplyType, TextContent } from "@/lib/types";

export const SAMPLE_CONTACT: Record<string, string> = {
  first_name: "Asha",
  last_name: "Verma",
  full_name: "Asha Verma",
  phone_number: "919812345670",
  email: "asha@example.com",
  country: "IN",
  language_code: "en",
};

/** Same substitution the server does, with a sample contact; unknown placeholders stay visible. */
export function sampleText(text: string, custom: Record<string, string> = {}) {
  return text.replace(/\{([a-z][a-z0-9_]{0,49})\}/gi, (whole, key: string) => {
    const k = key.toLowerCase();
    return SAMPLE_CONTACT[k] ?? custom[k] ?? whole;
  });
}

function MediaBlock({ kind, asset }: { kind: string; asset?: BotAsset | null }) {
  if (asset && kind === "image")
    // eslint-disable-next-line @next/next/no-img-element
    return <img src={asset.url} alt="" className="max-h-48 w-full rounded-md object-cover" />;
  const Icon = kind === "video" ? FileVideo : kind === "audio" ? FileAudio : FileText;
  return (
    <div className="flex items-center gap-2 rounded-md bg-black/5 px-3 py-3 text-[13px] text-[#54656f]">
      <Icon className="size-5 shrink-0" />
      <span className="truncate">{asset?.filename ?? `${kind[0].toUpperCase()}${kind.slice(1)}`}</span>
    </div>
  );
}

/** WhatsApp-style rendering of a bot reply, as the contact sees it. */
export function ReplyBubble({ type, content, assets, custom }: { type: ReplyType; content: TextContent | MediaContent | InteractiveContent; assets: Record<number, BotAsset>; custom?: Record<string, string> }) {
  const placeholder = <span className="text-[#8696a0]">Reply text</span>;
  if (type === "text") {
    const c = content as TextContent;
    return (
      <div className="max-w-[300px] rounded-lg rounded-tl-none bg-white px-3 py-2 text-[14px] leading-snug text-[#111b21] shadow-sm">
        <div className="whitespace-pre-wrap break-words">{c.body ? sampleText(c.body, custom) : placeholder}</div>
      </div>
    );
  }
  if (type === "media") {
    const c = content as MediaContent;
    return (
      <div className="max-w-[300px] space-y-1.5 rounded-lg rounded-tl-none bg-white p-1.5 text-[14px] leading-snug text-[#111b21] shadow-sm">
        <MediaBlock kind={c.media_type} asset={c.asset_id ? assets[c.asset_id] : null} />
        {c.caption && <div className="whitespace-pre-wrap break-words px-1.5 pb-0.5">{sampleText(c.caption, custom)}</div>}
      </div>
    );
  }
  const c = content as InteractiveContent;
  const a = c.action;
  return (
    <div className="max-w-[300px] overflow-hidden rounded-lg rounded-tl-none bg-white text-[14px] leading-snug text-[#111b21] shadow-sm">
      <div className="space-y-1.5 px-3 pb-2 pt-2.5">
        {c.header.type === "text" && c.header.text && <div className="font-semibold">{sampleText(c.header.text, custom)}</div>}
        {["image", "video", "document"].includes(c.header.type) && <MediaBlock kind={c.header.type} asset={c.header.asset_id ? assets[c.header.asset_id] : null} />}
        <div className="whitespace-pre-wrap break-words">{c.body ? sampleText(c.body, custom) : placeholder}</div>
        {c.footer && <div className="text-[12.5px] text-[#667781]">{sampleText(c.footer, custom)}</div>}
      </div>
      <div className="divide-y divide-[#e9edef] border-t border-[#e9edef] text-[13.5px] font-medium text-[#027eb5]">
        {a.type === "buttons" &&
          a.buttons.map((b, i) => (
            <div key={i} className="flex items-center justify-center gap-1.5 py-2">
              <Reply className="size-3.5" />
              {b.title || `Button ${i + 1}`}
            </div>
          ))}
        {a.type === "cta_url" && (
          <div className="flex items-center justify-center gap-1.5 py-2">
            <ExternalLink className="size-3.5" />
            {a.display_text || "Open link"}
          </div>
        )}
        {a.type === "list" && (
          <div className="flex items-center justify-center gap-1.5 py-2">
            <List className="size-3.5" />
            {a.button || "View options"}
          </div>
        )}
      </div>
      {a.type === "list" && (
        <div className="border-t border-[#e9edef] bg-[#f7f8fa] px-3 py-2 text-[12.5px]">
          {a.sections.map((s, i) => (
            <div key={i} className="py-1">
              {s.title && <div className="mb-0.5 text-[11px] font-semibold uppercase tracking-wide text-teal">{s.title}</div>}
              {s.rows.map((r, j) => (
                <div key={j} className="py-0.5">
                  <div className="text-[#111b21]">{r.title || `Option ${j + 1}`}</div>
                  {r.description && <div className="text-[#667781]">{r.description}</div>}
                </div>
              ))}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
