import {
  AbsoluteFill,
  Img,
  useCurrentFrame,
  interpolate,
  Easing,
} from "remotion";
import { useMemo } from "react";

function hashCode(str: string) {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = (hash << 5) - hash + str.charCodeAt(i);
    hash |= 0;
  }
  return Math.abs(hash);
}

export const SceneInstagramComment: React.FC<{
  backgroundImage: string;
  words: { text: string; delay: number; style?: React.CSSProperties }[];
  imageAnimation?: "zoomIn" | "rolling" | null;
  textAnimation?: "typewriter" | "bounceIn" | null;
}> = ({
  backgroundImage,
  words,
  imageAnimation = null,
  textAnimation = null,
}) => {
  const frame = useCurrentFrame();

  const emojiOptions = [
    "🐶",
    "🐱",
    "🐰",
    "🐻",
    "🐼",
    "🦊",
    "🐨",
    "🐥",
    "🐧",
    "🐝",
    "🦄",
    "🧸",
    "👶",
    "🧑",
    "👩‍🦰",
    "🧔",
    "👩‍🎨",
    "👨‍🚀",
    "🧑‍🍳",
    "🧑‍🎤",
    "🎨",
    "🎵",
    "✨",
    "❤️",
  ];

  const emojiUsernameMap = {
    "🐶": ["doggo_", "puplover_", "woofwoof_", "fetcher_"],
    "🐱": ["catlady_", "meowtime_", "kittylover_", "purrfect_"],
    "🐰": ["bunnyhop_", "fluffytail_", "hopster_", "carrotqueen_"],
    "🐻": ["bearhug_", "grizzlyfan_", "cuddlebear_", "bearycute_"],
    "🐼": ["panda_express_", "pandabear_", "bamboobuddy_", "pandadream_"],
    "🦊": ["foxy_", "quickfox_", "sneakyfox_", "wildtail_"],
    "🐨": ["koalasmile_", "treehugger_", "eucalyptus_", "koalacutie_"],
    "🐥": ["chicklet_", "yellowfeather_", "hatchling_", "peep_peep_"],
    "🐧": ["penguindash_", "frostyfeet_", "icewaddle_", "penguinlove_"],
    "🐝": ["buzzbuzz_", "honeymaker_", "beebuddy_", "sting_op_"],
    "🦄": ["unicorn_magic_", "rainbowrider_", "mystichorn_", "sparklequeen_"],
    "🧸": ["teddybear_", "cuddletime_", "softhug_", "plushfan_"],
    "👶": ["cutiepie_", "babyface_", "littleone_", "tinytoes_"],
    "🧑": ["user_", "friendlyface_", "defaultuser_", "profilepic_"],
    "👩‍🦰": ["redhair_", "gingerfan_", "fierylocks_", "scarlet_"],
    "🧔": ["beardbro_", "hairyfriend_", "beardlove_", "facefur_"],
    "👩‍🎨": ["artlover_", "paintbrush_", "gallerygoer_", "colorfulmind_"],
    "👨‍🚀": ["spacecadet_", "starman_", "galaxyfan_", "orbitguy_"],
    "🧑‍🍳": ["chefmaster_", "foodie_", "panfan_", "cookwithme_"],
    "🧑‍🎤": ["singstar_", "micdrop_", "karaokeking_", "musicfan_"],
    "🎨": ["colorlover_", "artaddict_", "paintlife_", "canvasdream_"],
    "🎵": ["musiclover_", "melody_", "beatdrop_", "soundwave_"],
    "✨": ["starlight_", "sparklevibes_", "shineon_", "glowup_"],
    "❤️": ["lovelife_", "heartfelt_", "romantic_", "lovestory_"],
  };

  const seed = useMemo(
    () => hashCode(words.map((w) => w.text).join(" ")),
    [words],
  );
  const randomEmoji = emojiOptions[seed % emojiOptions.length];
  const baseNames = emojiUsernameMap[randomEmoji] || ["user_"];
  const randomBase = baseNames[seed % baseNames.length];
  const randomNumber = seed % 10000;
  const username = `${randomBase}${randomNumber}`;

  const activeWords = words
    .filter((word) => frame >= word.delay)
    .map((word) => word.text)
    .join(" ");

  // Image animation styles
  const imageStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    objectFit: "cover",
    position: "absolute",
    top: 0,
    left: 0,
    zIndex: 0,
    transform: undefined,
  };

  if (imageAnimation === "zoomIn") {
    const scale = interpolate(frame, [0, 100], [1, 1.2], {
      extrapolateRight: "clamp",
    });
    imageStyle.transform = `scale(${scale})`;
  } else if (imageAnimation === "rolling") {
    const rotate = interpolate(frame, [0, 100], [0, 360]);
    imageStyle.transform = `rotate(${rotate}deg)`;
  }

  // Text animation styles
  const textAnimationStyle: React.CSSProperties = {};
  if (textAnimation === "bounceIn") {
    const bounce = interpolate(frame, [0, 15, 30], [0, 1.2, 1], {
      easing: Easing.bounce,
    });
    const opacity = interpolate(frame, [0, 15], [0, 1], {
      extrapolateRight: "clamp",
    });
    textAnimationStyle.transform = `scale(${bounce})`;
    textAnimationStyle.opacity = opacity;
  }

  return (
    <AbsoluteFill
      style={{
        backgroundColor: "#fff",
        position: "relative",
        fontFamily: "Arial, sans-serif",
      }}
    >
      {/* Background Image */}
      <Img src={backgroundImage} style={imageStyle} />

      {/* Comment Box */}
      <div
        style={{
          position: "absolute",
          top: "50%",
          transform: "translateY(-50%)",
          width: "100%",
          background: "rgba(255, 255, 255, 0.95)",
          borderRadius: "24px",
          padding: "80px",
          boxShadow: "0 12px 50px rgba(0, 0, 0, 0.3)",
          display: "flex",
          alignItems: "flex-start",
          gap: "24px",
          zIndex: 1,
          flexDirection: "row",
          flexWrap: "wrap",
        }}
      >
        {/* Profile Picture */}
        <div
          style={{
            width: "80px",
            height: "80px",
            backgroundColor: "#eee",
            borderRadius: "50%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: "48px",
            flexShrink: 0,
          }}
        >
          {randomEmoji}
        </div>

        {/* Text Content */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              fontWeight: "bold",
              color: "#262626",
              fontSize: "28px",
              marginBottom: "16px",
            }}
          >
            {username}
          </div>

          <div
            style={{
              color: "#262626",
              lineHeight: 1.6,
              fontSize: activeWords.length > 20 ? "60px" : "90px",
              wordWrap: "break-word",
              overflowWrap: "break-word",
              ...textAnimationStyle,
            }}
          >
            {activeWords}
            {textAnimation === "typewriter" && (
              <span style={{ opacity: 0.3 }}>|</span>
            )}
          </div>

          <div
            style={{ marginTop: "16px", fontSize: "16px", color: "#8e8e8e" }}
          >
            1m ago · See translation
          </div>
        </div>
      </div>
    </AbsoluteFill>
  );
};
