import React from "react";
import {
  AbsoluteFill,
  Audio,
  Img,
  Sequence,
  useCurrentFrame,
  useVideoConfig,
  interpolate,
} from "remotion";

export type SceneProp = {
  imagePath: string; // absolute path inside docker /data/media/..
  audioPath?: string;
  ambientPath?: string;
  subtitle?: string;
  durationInFrames: number;
};

export type MainVideoProps = {
  scenes: SceneProp[];
  musicPath?: string;
};

export const MainVideo: React.FC<MainVideoProps> = ({ scenes, musicPath }) => {
  const { fps } = useVideoConfig();

  // Helper: map local absolute path to standard file:// URL so Remotion Chromium can load it
  const makeFileUrl = (path?: string) => {
    if (!path) return undefined;
    if (path.startsWith("http")) return path;
    if (path.startsWith("file://")) return path;
    return `file://${path}`;
  };

  let currentStartFrame = 0;

  return (
    <AbsoluteFill style={{ backgroundColor: "black" }}>
      {/* Background Music */}
      {musicPath && <Audio src={makeFileUrl(musicPath)} volume={0.15} />}

      {scenes.map((scene, index) => {
        const startFrame = currentStartFrame;
        currentStartFrame += scene.durationInFrames;

        return (
          <Sequence
            key={index}
            from={startFrame}
            durationInFrames={scene.durationInFrames}
          >
            <SceneRenderer scene={scene} index={index} />
          </Sequence>
        );
      })}
    </AbsoluteFill>
  );
};

const SceneRenderer: React.FC<{ scene: SceneProp; index: number }> = ({ scene, index }) => {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();

  // Ken Burns Effect (Zoom In / Pan)
  // Even scenes zoom in, odd scenes zoom out slightly for variation
  const scale = interpolate(
    frame,
    [0, scene.durationInFrames],
    index % 2 === 0 ? [1, 1.1] : [1.1, 1],
    { extrapolateRight: "clamp" }
  );

  const makeFileUrl = (path?: string) => {
    if (!path) return undefined;
    if (path.startsWith("http")) return path;
    if (path.startsWith("file://")) return path;
    return `file://${path}`;
  };

  return (
    <AbsoluteFill style={{ overflow: "hidden" }}>
      <AbsoluteFill
        style={{
          transform: `scale(${scale})`,
          transformOrigin: "center center",
        }}
      >
        {scene.imagePath ? (
          <Img
            src={makeFileUrl(scene.imagePath)}
            style={{ width: "100%", height: "100%", objectFit: "cover" }}
          />
        ) : (
          <AbsoluteFill style={{ backgroundColor: "#111", justifyContent: "center", alignItems: "center" }}>
            <div style={{ color: "rgba(255, 255, 255, 0.2)", fontSize: "80px", fontFamily: "sans-serif", textAlign: "center", padding: "40px" }}>
              Visual Not Generated
            </div>
          </AbsoluteFill>
        )}
      </AbsoluteFill>

      {/* Audio Tracks */}
      {scene.audioPath && <Audio src={makeFileUrl(scene.audioPath)} />}
      {scene.ambientPath && <Audio src={makeFileUrl(scene.ambientPath)} volume={0.3} />}

      {/* Subtitles Overlay */}
      {scene.subtitle && (
        <AbsoluteFill
          style={{
            justifyContent: "flex-end",
            alignItems: "center",
            paddingBottom: "80px",
          }}
        >
          <div
            style={{
              backgroundColor: "rgba(0, 0, 0, 0.6)",
              color: "white",
              padding: "15px 30px",
              borderRadius: "15px",
              fontSize: "48px",
              fontFamily: "sans-serif",
              textAlign: "center",
              maxWidth: "80%",
              boxShadow: "0 4px 6px rgba(0,0,0,0.3)",
            }}
          >
            {scene.subtitle}
          </div>
        </AbsoluteFill>
      )}
    </AbsoluteFill>
  );
};
