"use client";

import { useState } from "react";
import useAxios from "@/hooks/useAxios";
import BoldIcon from "@/components/ui/BoldIcon";
import GiftRevealModal from "./GiftRevealModal";
import { useTranslation } from "react-i18next";

export interface SharedGiftPayload {
  giftId: string;
  amount: number;
  message?: string | null;
}

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

export default function SharedGiftBubble({
  data,
  isSender,
}: {
  data: SharedGiftPayload;
  isSender: boolean;
}) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [revealed, setRevealed] = useState(false);

  const handleOpen = () => {
    setRevealed(true);
    if (!isSender && data.giftId) {
      void request("POST", `/gifts/${data.giftId}/open`, {}, { noToast: true }).catch(
        () => {}
      );
    }
  };

  return (
    <>
      <button
        type="button"
        onClick={handleOpen}
        className="flex w-[210px] flex-col items-center gap-2 rounded-2xl border border-white/20 bg-gradient-to-b from-pink-500/25 to-purple-500/25 px-4 py-5 text-center active:scale-[0.98]"
      >
        <BoldIcon name="gift" size={36} tinted className="text-pink-300" />
        <span className="text-xs font-semibold opacity-90">
          {t("chats.gift.tapToOpen")}
        </span>
      </button>
      <GiftRevealModal
        isOpen={revealed}
        onClose={() => setRevealed(false)}
        amount={data.amount}
        message={data.message}
      />
    </>
  );
}
