//@ts-nocheck
import { Composition, Still } from 'remotion'
import React from 'react'
import { SequentialScene, SequentialSceneData } from './youtube/SequentialScene';
import Script from '../public/original_manuscript.json'
import { PosterSingleTextWithBG } from './common/PosterSingleTextWithBG';
import { YoutubeCategoriesConfig } from './models/Categories';
import './style.css';
import Transitions from '../public/assets/transitions.json'
import { IGReelComposition } from './ig-reel/IGReelComposition';
import { RenderUtils } from './RenderUtils';
import { VideoSplash, VideoSplashSchema } from './anims/VideoSplash';
import { YoutubeVideoScene } from './youtube/YoutubeVideoScene';
import { LinkedinFullSysDesignComposition } from './linkedin-video/LinkedinFullSysDesignComposition';
import { PaperDriveComposition } from './paperdrive/PaperDriveComposition';
import { PaperDriveHorizontalCoverComposition } from './paperdrive/PaperDriveHorizontalCoverComposition';
import { PosterSingleTextWithBGExtra, Transcript, TweetExtra } from 'common-utils';
import TweetPoster from './common/TweetPoster';






const playListsColors = {
    [YoutubeCategoriesConfig.PLAY_LIST_NAMES.SCIENCE_AND_TECHNOLOGY]: {
        textBgColor: "#301E67",
        brightColor: "#FFEA20"
    },
    [YoutubeCategoriesConfig.PLAY_LIST_NAMES.AMAZING_UNIVERSE]: {
        textBgColor: "#400E32",
        brightColor: "#F2CD5C"
    },
    [YoutubeCategoriesConfig.PLAY_LIST_NAMES.HISTORY_AND_POLITICS]: {
        textBgColor: "#0F6292",
        brightColor: "#F2CD5C"
    },
    [YoutubeCategoriesConfig.PLAY_LIST_NAMES.CURRENT_AND_NEWS]: {
        textBgColor: "#E90064",
        brightColor: "#FFED00"
    }
}


export const Compositions: React.FC = () => {

    let fps = Script?.meta?.fps
    if (!fps) {
        Script.meta.fps = 24
        fps = 24
    }
    var durationInSec = 0
    var lastDirection = false;

    let preloadImages = []
    let preloadVideos = []

    let contents: SequentialSceneData[] =
        Script.transcript
            .sort((t, u) => t.index - u.index)
            // .filter(item => (item.audioCaptionFile != undefined))
            // .slice(0, 2)
            .map((section, idx, array) => {
                section.index = section.index || idx;
                var { text, duration: durationMilis, offset, mediaAbsPaths, mediaAbsPaths, audioFullPath, title, pointers } = section
                mediaAbsPaths = mediaAbsPaths || mediaAbsPaths || []
                if (!durationMilis) {
                    durationMilis = section.durationInSeconds * 1000
                }
                if (!durationMilis)
                    durationMilis = 10e3
                // maybe required for youtube composition !!!
                let curDurSecs = (durationMilis / 1e3)
                if (curDurSecs < 3) {
                    curDurSecs = 3
                }
                //@ts-ignore
                const transitionFile = (section?.transition_file || Transitions[0].file)
                const transition_type = (section?.transition_type)
                if (transition_type && transition_type != 'none') {
                    section.transition_duration_sec = section?.transition_duration_sec || 0.5
                }
                //@ts-ignore
                const transitionDurationSec = (section?.transition_duration_sec || (transition_type && transition_type != 'none') ? 0.5 : 0)
                const transitionDurationFrames = transitionDurationSec * fps


                let commDuration = durationInSec //+ transitionDurationSec
                durationInSec = durationInSec + curDurSecs;///+ transitionDurationSec
                lastDirection = !lastDirection
                mediaAbsPaths.forEach(p => {
                    let im = p.path
                    if (im.startsWith("http")) {
                        if (im.indexOf("-video-") > -1 || im.indexOf(".mp4") > -1 || im.indexOf(".webm") > -1) {
                            preloadVideos.push(im)
                            // preloadVideo(im)
                        }
                        else {
                            preloadImages.push(im)
                            // preloadImage(im)
                        }
                    }
                })
                let bgImagePaths = mediaAbsPaths.map(p => {
                    p.path = RenderUtils.getFileName(p?.path)
                    return p
                })
                if (!offset) {
                    offset = commDuration
                }
                let frame = Object.assign(section, {
                    "commulativeDurationStartSec": commDuration,
                    "text": text,
                    "transition_file": RenderUtils.getFileName(transitionFile),
                    "durationInSecs": curDurSecs,
                    "duration": Math.ceil(curDurSecs * fps),
                    "offset": offset * fps,
                    "direction": lastDirection ? 'left' : 'right',
                    "bgImagePaths": bgImagePaths,
                    "audioPath": RenderUtils.getFileName(audioFullPath),
                    "textColor": '#F44336',
                    "emphasisOnImage": title?.length > 0 && pointers?.length > 0 || Script.meta.emphasisOnImage
                })

                return frame
            })

    console.log('contents', contents)
    const intro = {
        durationInFrames: 0,
        durationInSec: 5.433,
        file: Script.meta.tenantVideoConfig ? RenderUtils.getFileName(Script.meta.tenantVideoConfig.introFile, "assets") : 'assets/music_intro.mp4'
    }
    let ADJUST_END_DUR_SEC = 3
    const outro = {
        durationInFrames: 0,
        durationInSec: 8.034 - ADJUST_END_DUR_SEC,
        file: Script.meta.tenantVideoConfig ? RenderUtils.getFileName(Script.meta.tenantVideoConfig.outroFile, "assets") : 'assets/music_outro.mp4'
    }

    if (intro && Script?.meta?.tenantVideoConfig?.introFile) {
        durationInSec += intro.durationInSec
        intro.durationInFrames = Math.ceil(fps * intro.durationInSec)
    }

    if (outro && Script?.meta?.tenantVideoConfig?.outroFile) {
        durationInSec += outro.durationInSec
        //hack for blank end
        outro.durationInSec += 30
        outro.durationInFrames = Math.ceil(fps * outro.durationInSec)
    }

    // durationInSec = 10
    const duration = Math.ceil(durationInSec * fps)
    console.log("Total Video Duration", durationInSec)

    //@ts-ignore
    const playListsIDs = YoutubeCategoriesConfig.GET_PLAY_LIST_IDS(Script.meta?.userId || "104349087108535511186")

    return (
        <>
            <Composition
                id="SemibitComposition"
                component={YoutubeVideoScene}
                durationInFrames={duration}
                fps={fps}
                width={Script.meta?.resolution?.width || 1920}
                height={Script.meta?.resolution?.height || 1080}
                defaultProps={{
                    bgMusic: RenderUtils.getFileName(Script.bgMusic),
                    contents: contents,
                    intro: intro,
                    outro: outro,
                    meta: Script.meta
                }}
            />
            <Composition
                id='IGReelComposition'
                component={IGReelComposition}
                durationInFrames={duration}
                fps={fps}
                width={Script.meta?.resolution?.width || 1920}
                height={Script.meta?.resolution?.height || 1080}
                defaultProps={Object.assign(Script, {
                    bgMusic: RenderUtils.getFileName(Script.bgMusic),
                    contents: contents,
                    intro: intro,
                    outro: outro
                })}
            />

            <Composition
                id='LinkedinFullSysDesignComposition'
                component={LinkedinFullSysDesignComposition}
                durationInFrames={duration}
                fps={fps}
                width={Script.meta?.resolution?.width || 1920}
                height={Script.meta?.resolution?.height || 1080}
                defaultProps={Object.assign(Script, {
                    bgMusic: RenderUtils.getFileName(Script.bgMusic),
                    contents: contents,
                    intro: intro,
                    outro: outro
                })}
            />

            <Composition
                id='PaperDriveComposition'
                component={PaperDriveComposition}
                durationInFrames={(Script.meta.fps * Script.transcript.filter(transcript => ['index', 'page'].includes(transcript.extras?.template)).length) || 1}
                fps={fps}
                width={Script.meta?.resolution?.width || 1920}
                height={Script.meta?.resolution?.height || 1080}
                defaultProps={Object.assign(Script)}
            />

            <Composition
                id='PaperDriveHorizontalCoverComposition'
                component={PaperDriveHorizontalCoverComposition}
                durationInFrames={1}
                fps={fps}
                height={parseInt(`${812 * 1.5}`)}
                width={parseInt(`${1258.9006153846171 * 1.5}`)}
                defaultProps={Object.assign(Script)}
            />
            <Composition
                defaultProps={{
                    direction: 'left',
                    progress: 1,
                    file: 'effect_hexagon.webm',
                    durationInFrames: 200,
                }}
                schema={VideoSplashSchema}
                id='VideoSplash'
                component={VideoSplash}
                durationInFrames={100}
                fps={fps}
                width={Script.meta?.resolution?.width || 1920}
                height={Script.meta?.resolution?.height || 1080}
            />

            <Still
                id="SemibitCompositionPoster"
                component={PosterSingleTextWithBG}
                width={Script.meta.resolution?.width || 1920}
                height={Script.meta.resolution?.height || 1080}
                defaultProps={
                    Script.transcript.find(t => t.extras?.template == "poster-single-text-with-bg")
                    ||
                    {
                        extras: {
                            emphasisOnImage: Script.meta.emphasisOnImage,
                            text: (Script.meta?.posterTitle || Script.meta?.title)?.trim(),
                            textColor: '#fff',
                            textBgColor: playListsColors[Script.meta?.platlistName]?.textBgColor || "#E90064",
                            brightColor: playListsColors[Script.meta?.platlistName]?.brightColor || "#FFED00", 
                        } as PosterSingleTextWithBGExtra,
                        mediaAbsPaths: [{
                            path:
                                RenderUtils.getFileName(Script.meta?.posterImage) ||
                                    playListsIDs[Script.meta?.platlistName] ? ("assets/" + (playListsIDs[Script.meta?.platlistName])) : undefined,
                            type: 'image',
                        }]
                    } as Transcript}
            />

            <Still
                id="TweetPoster"
                component={TweetPoster}
                width={Script.meta.resolution?.width || 1920}
                height={Script.meta.resolution?.height || 1080}
                defaultProps={
                    {
                        transcript: Script.transcript.find(t => t.extras?.template == "tweet"),
                        meta: Script.meta
                    }
                }
            />
        </>
    );
};



const lightColors = [
    // "#E57373",
    // "#F06292",
    // "#BA68C8",
    // "#64B5F6",
    // "#64B5F6",
    // "#4DB6AC",
    // "#81C784",
    // "#DCE775",
    // "#FFD54F",
    // "#FF8A65",
    // "#FFFFFF"


    '#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5',
    '#2196F3', '#03A9F4', '#00BCD4', '#009688', '#4CAF50',
    '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
    '#FF5722', '#795548', '#9E9E9E', '#607D8B'
];

function getRandomLightColor() {
    const removeYellow = lightColors.filter(color => color !== '#FFC107' && color !== '#FFEB3B');

    return removeYellow[Math.floor(Math.random() * removeYellow.length)];
}