import { convertFileSrc } from '@tauri-apps/api/core'
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';

export interface OnSourceLoaded {
    (player: HTMLVideoElement | null): void;
}
export interface OnPlayerError {
    (err: Error, player: HTMLVideoElement | null): void;
}
export interface OnPlayerTimeChange {
    (player: HTMLVideoElement | null): void;
}
export interface LiveStreamPlayerRef {
    seek(time: number): void;
    pause(): void;
    play(): void;
    getCurrentTime(): number;
    isPaused(): boolean;
    getDuration(): number;
    captureFrame(): string | undefined;
    fullScreen(): void;
}

export const VideoPlayer2: React.FC<{
    src?: string;
    ref?: React.RefObject<LiveStreamPlayerRef | null>;
    onSourceLoaded?: OnSourceLoaded;
    onError?: OnPlayerError;
    onTimeChange?: OnPlayerTimeChange;
}> = ({ src, onSourceLoaded, onError, onTimeChange, ref }) => {
    const videoRef = useRef<HTMLVideoElement>(null);
    const [isLoading, setIsLoading] = useState(true);


    useImperativeHandle(ref, () => ({
        seek: (time: number) => {
            videoRef.current && (videoRef.current.currentTime = time);
        },
        pause: () => {
            videoRef.current?.pause();
        },
        play: () => {
            videoRef.current?.play();
        },
        isPaused: () => {
            return !!videoRef.current?.paused;
        },
        getCurrentTime: () => {
            return videoRef.current?.currentTime || 0;
        },
        getDuration: () => {
            return videoRef.current?.duration || 0;
        },
        captureFrame: () => {
            const video = videoRef.current;
            if (!video) return;
            // 创建canvas元素
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            if (!ctx) return;
            // 设置canvas尺寸
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;

            // 上传到modal
            // 绘制视频帧到canvas
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            const dataURL = canvas.toDataURL('image/jpeg', 0.05);
            return dataURL;
        },
        fullScreen: () => {
            const video = videoRef.current;
            if (video) {
                video.requestFullscreen();
            }
        },
    }));

    useEffect(() => {
        const video = videoRef.current;
        if (!video) return;

        const showLoading = () => setIsLoading(true);
        const hideLoading = () => setIsLoading(false);

        video.addEventListener('waiting', showLoading);
        video.addEventListener('seeking', showLoading);

        video.addEventListener('playing', hideLoading);
        video.addEventListener('seeked', hideLoading);
        video.addEventListener('canplay', hideLoading);

        return () => {
            if (!video) return;
            video.removeEventListener('waiting', showLoading);
            video.removeEventListener('seeking', showLoading);
            video.removeEventListener('playing', hideLoading);
            video.removeEventListener('seeked', hideLoading);
            video.removeEventListener('canplay', hideLoading);
        };
    }, []);

    useEffect(() => {
        const video = videoRef.current;
        if (!video) return;
        video.addEventListener('loadedmetadata', (a) => {
            return onSourceLoaded && onSourceLoaded(video);
        });
        video.addEventListener('timeupdate', () => onTimeChange && onTimeChange(video));
        video.addEventListener('error', () => onError && onError(new Error('Video error'), video));

        video.src = convertFileSrc(src!);
        return () => {
            if (video) {
                video.src = '';
            }
        };
    }, [src]);

    return (
        <div className="relative h-full w-full">
            <video ref={videoRef} crossOrigin="anonymous" className="h-full w-full bg-[#18181A]" autoPlay preload="auto" />
            {isLoading && (
                <div className="absolute inset-0 flex items-center justify-center">
                    <div className="h-12 w-12 animate-spin rounded-full border-4 border-solid border-white border-t-transparent" />
                </div>
            )}
        </div>
    );
};
