import React from "react"
import { __ } from '@wordpress/i18n'
import VideoCardInterface from "Interfaces/VideoCardInterface"
import { getTimeString, getDateString } from "../../Libs/TimeConveter"
import { STORE_KEY } from "../../Stores/VideoStore"
import { select, dispatch } from "@wordpress/data"
// import { createBlock, getBlockType } from '@wordpress/blocks'
import { CreateCustomEvent } from "../../Libs/CustomEvent"

interface VideoCardDataProps {
    videoData?: VideoCardInterface
    feedbackController?: (type: string, message: string) => void
}


const checkEditorMode = (): "gutenberg" | "classic-editor" => {
    if (document.body.classList.contains('block-editor-page')) {
        return 'gutenberg'
    }

    return 'classic-editor'
}
const editorMode = checkEditorMode()

const VideoCardComponent: React.FC<VideoCardDataProps> = ({ videoData, feedbackController }) => {
    const createdTime = typeof videoData.created_time === 'number' ? videoData.created_time : null
    const createdTimeLabel = createdTime !== null ? getDateString(createdTime) : ''
    const durationLabel = videoData.videos_total
        ? videoData.videos_total
        : (typeof videoData.duration === 'number' ? getTimeString(videoData.duration) : '')
    const handleClick = () => {
        if (editorMode === "gutenberg") {
            const { getSelectedBlock, getBlocks } = select('core/block-editor')

            let targetBlock = getSelectedBlock()

            // Check if the selected block is a Dailymotion player block
            if (!targetBlock || targetBlock.name !== 'dm-pro/embed-video') {
                feedbackController && feedbackController('feedback-error', __('Please select a Dailymotion player block to update the video', 'textdomain'))
            } else {
                // @ts-ignore
                dispatch(STORE_KEY).setVideo(videoData)
                CreateCustomEvent('dm-video-updated', 'dm-video-component')
                feedbackController && feedbackController('feedback-success', __('Video updated successfully', 'textdomain'))
            }
        } else {
            let attrsString = ''

            if (videoData.private === true) {
                attrsString += ' privatevideoid="' + videoData.private_id + '"'
            } else if (typeof videoData.name !== 'undefined') {
                attrsString += ' playlistid="' + videoData.id + '"'
            } else {
                attrsString += ' videoid="' + videoData.id + '"'
            }

            // @ts-ignore
            wp.media.editor.insert('[dm-player' + attrsString + ']')
            CreateCustomEvent('dm-video-updated', 'dm-video-component')
            feedbackController && feedbackController('feedback-success', __('Video updated successfully', 'textdomain'))
        }
    }


    return (
        <div className="item-wrapper" tabIndex={0} onClick={handleClick}>
            <img src={videoData.thumbnail_480_url} alt={videoData.title || videoData.name} className="vfp-thumbnail-img" loading="lazy" />

            <div className="vfp-video-info">
                <div className="vfp-info-top">
                    <time className="vfp-created" dateTime={createdTimeLabel}>
                        {createdTimeLabel}
                    </time>
                    <div className={videoData.videos_total ? "vfp-video-total" : "vfp-duration"}>{durationLabel}</div>
                </div>
                <div className="vfp-video-owner">
                    <img src={videoData["owner.avatar_60_url"]} />
                    <div className="vfp-owner-name">{videoData["owner.screenname"]}</div>
                </div>
                <div className="vfp-title">{videoData.title ? videoData.title : videoData.name}</div>
            </div>
            <div className=" video-preview"></div>
        </div>
    )
}

interface SearchResultComponentProps {
    videoResult: VideoCardInterface[]
    feedbackController?: (type: string, message: string) => void
}

const SearchResultComponent: React.FC<SearchResultComponentProps> = ({ videoResult, feedbackController }) => {
    return (
        <div id="searchResult" className="search-result">
            { videoResult.map((videoData, index) => (
                <VideoCardComponent key={index} videoData={videoData} feedbackController={feedbackController}></VideoCardComponent>
            ))}
        </div>
    )
}

export default SearchResultComponent
