import React, {useState, useRef} from "react";
import SearchInfo from "./SearchInfo";
import SearchBar from "./SearchBar";
import {
    getThumb,
    isAudioVideoType,
    isVideoType,
    isFolder,
    humanFileSize,
    humanDuration,
    useHandleListingResize, formatDateForSQL
} from "../../../includes/functions";

export default function Playlist({
                                     file,
                                     files,
                                     setFile,
                                     folderFiles,
                                     setFolderFiles,
                                     getFolderFiles,
                                     isSub,
                                     isPlaying,
                                     setIsPlaying,
                                     download,
                                     activeFolder,
                                     setActiveFolder,
                                     playlistThumbnail,
                                     playlistNumber,
                                     allowSearch,
                                     initParentFolder,
                                     initFolders,
                                     filters,
                                     privateFolders,
                                     fullTextSearch,
                                     initialSearchTerm,
                                     sort,
                                     setFiles,
                                     isSearchResults,
                                     setIsSearchResults,
                                     searchKeywordRef,
                                     notifications,
                                     nonce,
                                     playlistStyle,
                                     playlistItemDuration,
                                     playlistItemSize,
                                     playlistItemDate,
                                     allFiles,
                                 }) {
    const [openFolders, setOpenFolders] = useState([]);
    const [isLoading, setIsLoading] = useState(false);

    // Search states
    const [keyword, setKeyword] = useState(initialSearchTerm);
    const [error, setError] = useState(false);
    const [isActive, setIsActive] = useState(!!initialSearchTerm);

    // Ref for dynamic listing size class
    const containerRef = useRef();
    const listClass = useHandleListingResize(containerRef, playlistStyle !== "grid");

    // Find last folder index for break rendering (only in grid mode)
    const lastFolderTypeIndex =
        playlistStyle === "grid" && files.length
            ? files.reduce((acc, item, idx) => (isFolder(item) ? idx : acc), undefined)
            : undefined;

    // Go back to previous folder
    const handleBackClick = () => {
        const keys = Object.keys(folderFiles);
        const currentIndex = keys.indexOf(activeFolder);

        if (currentIndex > 0) {
            const prevFolder = keys[currentIndex - 1];
            setActiveFolder(prevFolder);
            setFiles(folderFiles[prevFolder]);
            setOpenFolders(openFolders =>
                openFolders.filter(folder => folder.id !== activeFolder)
            );
        } else {
            setActiveFolder(null);
            setFiles(allFiles[''] || initFolders);
            setFolderFiles({});
            setOpenFolders([]);
        }
    };

    // Handle item (file/folder) click
    const handleItemClick = (item, isDir, isActiveFolder, isOpen, e) => {
        e.stopPropagation();

        if (isDir) {
            setActiveFolder(isActiveFolder ? null : item.id);

            if (playlistStyle !== "grid") {
                setOpenFolders(openFolders =>
                    isOpen
                        ? openFolders.filter(folder => folder.id !== item.id)
                        : [...openFolders, item]
                );
                if (isOpen || (folderFiles && folderFiles[item.id])) return;
            } else if (folderFiles[item.id]?.length) {
                setFiles(folderFiles[item.id]);
                return;
            }
            getFolderFiles(item);
        } else {
            if (file && file.id === item.id) {
                setIsPlaying(!isPlaying || isPlaying === "pause");
            } else {
                setIsPlaying(true);
                setFile(item);
                if (isVideoType(item)) {
                    const parent = e.target.closest(".igd-player");
                    if (
                        parent &&
                        (parent.classList.contains("playlist-bottom") || window.innerWidth < 768)
                    ) {
                        parent.scrollIntoView({behavior: "smooth"});
                    }
                }
            }
        }
    };

    return (
        <div
            className={`${isSub ? "sub-item" : "igd-player-playlist"} ${listClass}`}
            ref={containerRef}
        >
            {/* Search bar and results */}
            {!isSub && allowSearch && (
                <>
                    <SearchBar
                        initFolders={initFolders}
                        initParentFolder={initParentFolder}
                        filters={filters}
                        sort={sort}
                        privateFolders={privateFolders}
                        setFiles={setFiles}
                        fullTextSearch={fullTextSearch}
                        initialSearchTerm={initialSearchTerm}
                        isSearchResults={isSearchResults}
                        setIsSearchResults={setIsSearchResults}
                        searchKeywordRef={searchKeywordRef}
                        isLoading={isLoading}
                        setIsLoading={setIsLoading}
                        notifications={notifications}
                        keyword={keyword}
                        setKeyword={setKeyword}
                        error={error}
                        setError={setError}
                        isActive={isActive}
                        setIsActive={setIsActive}
                        nonce={nonce}
                    />
                    {isSearchResults && !isLoading && (
                        <SearchInfo
                            files={files}
                            searchKeywordRef={searchKeywordRef}
                            setIsActive={setIsActive}
                            isActive={isActive}
                            setKeyword={setKeyword}
                            setError={setError}
                            setIsSearchResults={setIsSearchResults}
                            setFiles={setFiles}
                            initFolders={initFolders}
                            allFiles={allFiles}
                        />
                    )}
                </>
            )}

            {/* Back button (in folder grid) */}
            {!!activeFolder && (
                <div className="playlist-item-wrap folder-item-wrap" onClick={handleBackClick}>
                    <div className="playlist-item folder-item">
                        <i className="dashicons dashicons-arrow-left-alt2"></i>
                        {wp.i18n.__("Back", "integrate-google-drive")}
                    </div>
                </div>
            )}

            {/* Playlist items */}
            {files.length > 0 &&
                files.map((item, index) => {
                    const {id, name, size, updated, metaData} = item;

                    const iconSize =
                        playlistStyle === "grid"
                            ? {w: 256, h: 256}
                            : {w: 64, h: 64};

                    const icon = getThumb(item, "custom", iconSize);

                    const isDir = isFolder(item);
                    if (!isDir && !isAudioVideoType(item)) return null;

                    const isActiveFolder = id === activeFolder;
                    const isActiveFile = file?.id === id;
                    const isOpen = openFolders.some(folder => folder.id === item.id);

                    return (
                        <React.Fragment key={id}>

                            {lastFolderTypeIndex === index - 1 && (
                                <div className="playlist-item-wrap folder-item-break"></div>
                            )}

                            <div className={`playlist-item-wrap ${isDir ? "folder-item-wrap" : ""}`}
                                 onClick={e =>
                                     handleItemClick(item, isDir, isActiveFolder, isOpen, e)
                                 }
                            >
                                <div
                                    className={`playlist-item ${isActiveFile ? "active" : ""} ${
                                        isDir ? "folder-item" : ""
                                    }`}
                                >
                                    {playlistNumber && (
                                        <span className="item-index">
                                            {String(index + 1).padStart(2, "0")}.
                                        </span>
                                    )}

                                    {playlistStyle !== "grid" && isDir && (!isActiveFolder || !!folderFiles[id]) && (
                                        <span
                                            className={`dashicons ${
                                                isOpen
                                                    ? "dashicons-arrow-down"
                                                    : "dashicons-arrow-right"
                                            }`}
                                        ></span>
                                    )}

                                    {isActiveFolder && !folderFiles[id] && (
                                        <div className="igd-spinner"></div>
                                    )}

                                    {playlistThumbnail && <img src={icon} alt={name}/>}

                                    <span className="item-name">{name}</span>

                                    <div className="item-meta">

                                        {playlistItemDuration && !isDir && !!metaData?.duration && (
                                            <span className="item-duration">
                                                <i className="dashicons dashicons-clock"></i>
                                                {humanDuration(metaData.duration)}
                                            </span>
                                        )}

                                        {playlistItemSize && !isDir && !!size && (
                                            <span className="item-size">{humanFileSize(size)}</span>
                                        )}

                                        {playlistItemDate &&
                                            <span className="item-size">{formatDateForSQL(updated)}</span>
                                        }

                                    </div>

                                    {!isDir && isActiveFile && isPlaying && isPlaying !== "pause" && (
                                        <span className="dashicons dashicons-controls-pause"></span>
                                    )}
                                    {!isDir && (!isActiveFile || !isPlaying || isPlaying === "pause") && (
                                        <span className="dashicons dashicons-controls-play"></span>
                                    )}
                                </div>

                                {playlistStyle !== "grid" &&
                                    isOpen &&
                                    !!folderFiles[id] && (
                                        <Playlist
                                            isSub={true}
                                            files={folderFiles[id]}
                                            file={file}
                                            setFile={setFile}
                                            folderFiles={folderFiles}
                                            getFolderFiles={getFolderFiles}
                                            isPlaying={isPlaying}
                                            setIsPlaying={setIsPlaying}
                                            download={download}
                                            activeFolder={activeFolder}
                                            setActiveFolder={setActiveFolder}
                                            playlistThumbnail={playlistThumbnail}
                                            playlistNumber={playlistNumber}
                                            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}
                                            playlistItemDuration={playlistItemDuration}
                                            playlistItemSize={playlistItemSize}
                                            playlistItemDate={playlistItemDate}
                                        />
                                    )}
                            </div>
                        </React.Fragment>
                    );
                })}

            {/* No items message */}
            {files.length === 0 && !isLoading && (
                <div className="playlist-no-items">
                    <i
                        className={`dashicons dashicons-${
                            isSearchResults ? "search" : "open-folder"
                        }`}
                    ></i>
                    {wp.i18n.__("No items found", "integrate-google-drive")}
                </div>
            )}

        </div>
    );
}
