import Plyr from "./Player/Plyr";
import Playlist from "./Player/Playlist";
import {
    base64Encode,
    getThumb,
    isAudioType,
    isAudioVideoType,
    isFilePublic,
    isFolder,
    isVideoType,
    useMounted
} from "../../includes/functions";

const {useRef, useEffect, useState, useCallback, useMemo} = React;

const Player = ({
                    initFolders = [],
                    nextPrevious,
                    rewindForward,
                    allowEmbedPlayer,
                    playlistStyle,
                    download,
                    sort,
                    allowSearch,
                    initParentFolder,
                    filters,
                    privateFolders,
                    fullTextSearch = true,
                    initialSearchTerm,
                    showPlaylist = true,
                    openedPlaylist = true,
                    playlistPosition = 'bottom',
                    notifications,
                    playlistThumbnail,
                    playlistAutoplay,
                    playlistNumber,
                    nonce,
                    shortcodeId,
                    showPlaylistToggle,
                    allowPreviewPopout,
                    playlistItemDuration,
                    playlistItemSize,
                    playlistItemDate,
                }) => {

    // ---------- State ----------
    const [files, setFiles] = useState(initFolders);
    const [allFiles, setAllFiles] = useState({'': initFolders});


    const [folderFiles, setFolderFiles] = useState({});
    const [isLoop, setIsLoop] = useState(localStorage.getItem('igd_is_loop') === 'true');
    const [isShuffle, setIsShuffle] = useState(localStorage.getItem('igd_is_shuffle') === 'true');
    const [isOpenPlaylist, setIsOpenPlaylist] = useState(showPlaylist && (openedPlaylist || playlistStyle === 'grid'));
    const [activeFolder, setActiveFolder] = useState(null);
    const [isSearchResults, setIsSearchResults] = useState(false);
    const [breakpoint, setBreakpoint] = useState('lg');

    const searchKeywordRef = useRef(initialSearchTerm);
    const containerRef = useRef(null);

    // Filter playable items only once files change
    const playableItems = useMemo(() => files.filter(isAudioVideoType), [files]);

    // Set default file (first playable item) if current file is missing
    let initFile = playableItems.length ? playableItems[0] : null;

    const lastPlayedFileID = sessionStorage.getItem(`igd_playback_${shortcodeId}`);

    if (lastPlayedFileID) {
        initFile = playableItems.find(item => item.id === lastPlayedFileID) || initFile;
    }

    const [file, setFile] = useState(initFile);

    const [isPlaying, setIsPlaying] = useState(lastPlayedFileID === initFile?.id);

    useEffect(() => {
        if (!file && playableItems.length) setFile(playableItems[0]);
    }, [playableItems, file]);

    // ---------- Utility ----------
    const isMounted = useMounted();
    const isVideo = file && isVideoType(file);
    const isAudio = file && isAudioType(file);
    const currentIndex = file ? playableItems.findIndex(item => item.id === file.id) : 0;

    // ---------- Playlist Management ----------
    // Fetch files inside a folder and update playable items
    const getFolderFiles = useCallback((folder) => {
        wp.ajax.post('igd_get_files', {
            shortcodeId,
            data: {folder, sort, filters},
            nonce: nonce || igd.nonce,
            skipBreadcrumbs: true,
        }).done(({files: newFiles}) => {
            const filtered = newFiles.filter(item => isAudioVideoType(item) || isFolder(item));
            setFolderFiles(prev => ({...prev, [folder.id || folder]: filtered}));

            console.log(newFiles)

            setFiles(filtered);

            // Update the state with the new folder information
            setAllFiles(prevFiles => ({
                ...prevFiles,
                [folder.id]: filtered,
                folders: prevFiles.folders || [],
            }));

        });
    }, [shortcodeId, sort, filters, nonce]);

    // Next/Prev handlers with loop/shuffle logic
    const playNext = useCallback((isEnded = false) => {
        if (isEnded && isLoop) return;
        let nextFile;
        if (isShuffle) {
            nextFile = playableItems[Math.floor(Math.random() * playableItems.length)];
        } else {
            nextFile = playableItems[(currentIndex + 1) % playableItems.length];
        }
        setFile(nextFile);
        setIsPlaying(true);
    }, [isLoop, isShuffle, playableItems, currentIndex]);

    const playPrev = useCallback(() => {
        let prevIndex = currentIndex - 1;
        if (prevIndex < 0) prevIndex = playableItems.length - 1;
        setFile(playableItems[prevIndex]);
        setIsPlaying(true);
    }, [currentIndex, playableItems]);

    // ---------- Download ----------
    const handleDownload = useCallback(() => {
        if (!file) return;
        const downloadLink = `${igd.ajaxUrl}?action=igd_download&shortcodeId=${shortcodeId}&id=${file.id}&accountId=${file.accountId}&nonce=${nonce || igd.nonce}`;
        window.open(downloadLink, '_blank')?.focus();
        if (notifications?.downloadNotification) {
            wp.ajax.post('igd_notification', {
                files: [file],
                notifications,
                type: 'download',
                nonce: nonce || igd.nonce,
            });
        }
    }, [file, shortcodeId, nonce, notifications]);

    // ---------- LocalStorage Sync ----------
    useEffect(() => {
        if (isMounted) localStorage.setItem('igd_is_loop', isLoop);
    }, [isLoop, isMounted]);

    useEffect(() => {
        if (isMounted) localStorage.setItem('igd_is_shuffle', isShuffle);
    }, [isShuffle, isMounted]);

    // ---------- Notification on Play ----------
    useEffect(() => {
        if (isMounted && notifications?.playNotification && file) {
            wp.ajax.post('igd_notification', {
                files: [file],
                notifications,
                type: 'play',
                nonce: nonce || igd.nonce,
            });
        }
    }, [file, notifications, nonce, isMounted]);

    // ---------- Responsive Breakpoint ----------
    useEffect(() => {
        if (!containerRef.current) return;
        const breakpoints = {xs: 480, sm: 768, md: 992, lg: 1200};
        const resizeObserver = new ResizeObserver(entries => {
            const width = entries[0].contentRect.width;
            if (width <= breakpoints.xs) setBreakpoint('xs');
            else if (width <= breakpoints.sm) setBreakpoint('sm');
            else if (width <= breakpoints.md) setBreakpoint('md');
            else setBreakpoint('lg');
        });
        resizeObserver.observe(containerRef.current);
        return () => resizeObserver.disconnect();
    }, []);

    // ---------- Video Permission Public Update ----------
    useEffect(() => {
        if (
            allowEmbedPlayer &&
            file &&
            isVideoType(file) &&
            !isFilePublic(file) &&
            !igd.settings?.secureVideoPlayback
        ) {
            wp.ajax.post('igd_update_file_permission', {
                shortcodeId,
                file_id: file.id,
                account_id: file.accountId,
                nonce: nonce || igd.nonce,
            });
        }
    }, [allowEmbedPlayer, file, shortcodeId, nonce]);


    return (
        <div
            ref={containerRef}
            className={`
                igd-player
                playlist-${playlistPosition}
                playlist-${playlistStyle}
                ${isVideo ? 'type-video' : 'type-audio'}
                ${isPlaying ? 'active' : 'paused'}
                ${isLoop ? 'is-loop' : ''}
                ${isOpenPlaylist ? 'is-playlist' : ''}
                ${isShuffle ? 'is-shuffle' : ''}
                size-${breakpoint}
            `}
        >
            <div className="media-wrap">
                {isAudio && file && (
                    <div className="current-item">
                        <img src={getThumb(file, 'small')} alt={file.name}/>
                        <div className="item-caption">
                            <span className="item-title">{file.name}</span>
                            {file.description && <span className="item-description">{file.description}</span>}
                        </div>
                    </div>
                )}

                {file && !isAudio && allowEmbedPlayer && (
                    <iframe
                        src={
                            igd.settings?.secureVideoPlayback
                                ? `${igd.homeUrl}/?secure_embed=1&id=${base64Encode(file.id)}&account_id=${base64Encode(file.accountId)}&nonce=${igd.nonce}`
                                : `https://drive.google.com/file/d/${file.id}/preview`
                        }
                        width="100%"
                        height="100%"
                        allowFullScreen
                        allow="autoplay"
                        sandbox={allowPreviewPopout ? undefined : 'allow-scripts allow-same-origin'}
                    />
                )}

                {file && (!allowEmbedPlayer || isAudio) && (
                    <Plyr
                        file={file}
                        isPlaying={isPlaying}
                        setIsPlaying={setIsPlaying}
                        playNext={playNext}
                        playPrev={playPrev}
                        download={download}
                        showPlaylist={showPlaylist}
                        nextPrevious={nextPrevious}
                        rewindForward={rewindForward}
                        playableItems={playableItems}
                        handleDownload={handleDownload}
                        playlistAutoplay={playlistAutoplay}
                        isLoop={isLoop}
                        setIsLoop={setIsLoop}
                        isOpenPlaylist={isOpenPlaylist}
                        setIsOpenPlaylist={setIsOpenPlaylist}
                        isShuffle={isShuffle}
                        setIsShuffle={setIsShuffle}
                        shortcodeId={shortcodeId}
                        nonce={nonce || igd.nonce}
                    />
                )}

                {allowEmbedPlayer && !isAudio && files.length > 0 && (
                    <div className="igd-player-controls">
                        {nextPrevious && (
                            <>
                                <button
                                    className="igd-play-prev"
                                    onClick={playPrev}
                                    title={wp.i18n.__('Previous', 'integrate-google-drive')}
                                >
                                    <i className="dashicons dashicons-controls-skipback"/>
                                </button>
                                <button
                                    className="igd-play-next"
                                    onClick={playNext}
                                    title={wp.i18n.__('Next', 'integrate-google-drive')}
                                >
                                    <i className="dashicons dashicons-controls-skipforward"/>
                                </button>
                            </>
                        )}

                        {showPlaylist && showPlaylistToggle && (
                            <button
                                className="igd-toggle-playlist"
                                onClick={() => setIsOpenPlaylist(v => !v)}
                                title={wp.i18n.__('Toggle Playlist', 'integrate-google-drive')}
                            >
                                <i className="dashicons dashicons-playlist-video"/>
                            </button>
                        )}
                    </div>
                )}
            </div>

            {isOpenPlaylist && (
                <Playlist
                    file={file}
                    files={files}
                    setFile={setFile}
                    folderFiles={folderFiles}
                    setFolderFiles={setFolderFiles}
                    getFolderFiles={getFolderFiles}
                    isPlaying={isPlaying}
                    setIsPlaying={setIsPlaying}
                    download={download}
                    activeFolder={activeFolder}
                    setActiveFolder={setActiveFolder}
                    playlistThumbnail={playlistThumbnail}
                    playlistNumber={playlistNumber}
                    playlistStyle={playlistStyle}
                    playlistItemDuration={playlistItemDuration}
                    playlistItemSize={playlistItemSize}
                    playlistItemDate={playlistItemDate}
                    showPlaylist={showPlaylist}
                    allowSearch={allowSearch}
                    initParentFolder={initParentFolder}
                    initFolders={initFolders}
                    filters={filters}
                    privateFolders={privateFolders}
                    fullTextSearch={fullTextSearch}
                    initialSearchTerm={initialSearchTerm}
                    sort={sort}
                    setFiles={setFiles}
                    allFiles={allFiles}
                    isSearchResults={isSearchResults}
                    setIsSearchResults={setIsSearchResults}
                    searchKeywordRef={searchKeywordRef}
                    notifications={notifications}
                    nonce={nonce}
                />
            )}
        </div>
    );
};

export default Player;
