import type { ComponentType } from "react";
import type { Post } from "../../types/post";
import { useI18n } from "../../i18n";
import { TextBubble } from "./bubbles/TextBubble";
import { FileDocBubble } from "./bubbles/FileDocBubble";
import { ImageBubble } from "./bubbles/ImageBubble";
import { ImageWithTextBubble } from "./bubbles/ImageWithTextBubble";
import { AlbumBubble } from "./bubbles/AlbumBubble";
import { VideoBubble } from "./bubbles/VideoBubble";
import { formatDateTime } from "./utils/formatTime";

type BubbleComponent = ComponentType<{ post: Post }>;

export function pickBubble(post: Post): BubbleComponent {
  const a = post.attachments;
  if (a.length === 0) return TextBubble;
  if (a.length >= 2 && a.every((x) => x.kind === "image")) return AlbumBubble;
  const only = a[0];
  if (only.kind === "video") return VideoBubble;
  if (only.kind === "image") {
    return post.text ? ImageWithTextBubble : ImageBubble;
  }
  return FileDocBubble;
}

export function MessageBubble({ post }: { post: Post }) {
  const { lang } = useI18n();
  const Bubble = pickBubble(post);
  const isVisual =
    Bubble === AlbumBubble ||
    Bubble === VideoBubble ||
    Bubble === ImageBubble ||
    Bubble === ImageWithTextBubble;

  return (
    <div
      id={`post-${post.id}`}
      className="mx-auto w-full max-w-[358px] scroll-mt-20 md:max-w-[680px] md:scroll-mt-24 lg:max-w-[900px] xl:max-w-[1120px]"
    >
      <article
        className={`relative w-full overflow-hidden rounded-2xl bg-[#272632] text-left shadow-sm ${
          isVisual ? "p-0" : "px-4 py-3"
        }`}
      >
        <Bubble post={post} />
        <time
          dateTime={post.publishedAt}
          className={`block text-right text-[12px] leading-[19px] text-[#A8A9AE] ${
            isVisual ? "px-4 pb-3 pt-3" : "mt-3"
          }`}
        >
          {formatDateTime(post.publishedAt, lang)}
        </time>
      </article>
    </div>
  );
}
