"use client";

import Image from "next/image";
import Link from "next/link";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";

export interface SharedStoryPayload {
  storyId: string;
  mediaType?: "image" | "video";
  preview?: string;
  ownerUserName?: string;
  ownerDisplayName?: string;
  reactionType?: "like" | "comment";
}

export function parseSharedStory(content: string): SharedStoryPayload | null {
  if (!content) return null;
  try {
    const line = content.split("\n")[0];
    const j = JSON.parse(line);
    if (j?.e2ee) return null;
    return j.sharedStory ?? null;
  } catch {
    return null;
  }
}

export function extractStoryReactionText(content: string): string {
  if (!content) return "";
  const lines = content.split("\n");
  if (lines.length <= 1) return "";
  return lines.slice(1).join("\n").trim();
}

export default function SharedStoryBubble({
  data,
  reactionText,
}: {
  data: SharedStoryPayload;
  reactionText?: string;
}) {
  const { t } = useTranslation("common");
  const preview = data.preview ? buildStorageUrl(data.preview) : null;
  const isLike = data.reactionType === "like";

  return (
    <div className="block overflow-hidden rounded-xl border border-white/20 bg-black/10">
      <div className="flex items-center gap-1.5 px-2 pt-2 text-[10px] font-semibold opacity-80">
        <BoldIcon name="video-vertical" size={14} tinted className="text-current" />
        <span>
          {data.reactionType
            ? t("chats.shared.storyReply")
            : t("chats.shared.story")}
        </span>
        {data.ownerDisplayName || data.ownerUserName ? (
          <Link
            href={`/users/${data.ownerUserName}`}
            className="text-[#0095f6]"
            onClick={(e) => e.stopPropagation()}
          >
            {data.ownerDisplayName || data.ownerUserName}
          </Link>
        ) : null}
      </div>
      {preview && (
        <div className="relative mx-2 mt-1 aspect-[9/16] w-[120px] overflow-hidden rounded-lg bg-neutral-900">
          {data.mediaType === "video" ? (
            <video
              src={preview}
              className="h-full w-full object-cover"
              muted
              playsInline
              preload="metadata"
            />
          ) : (
            <Image
              src={preview}
              alt=""
              fill
              className="object-cover"
              unoptimized
            />
          )}
        </div>
      )}
      <div className="px-2 py-1.5">
        {isLike ? (
          <p className="text-xl leading-none">❤️</p>
        ) : reactionText ? (
          <p className="text-[13px] leading-snug">{reactionText}</p>
        ) : (
          <p className="text-[11px] opacity-70">{t("chats.shared.storyComment")}</p>
        )}
      </div>
    </div>
  );
}
