import {Modal} from "antd";
import {saveAs} from "file-saver";
import {useSetState} from "ahooks";
import {Player} from "@/components/video/player.tsx";

import {push2room} from "@/service/api/video.ts";
import {showErrorToast, showToast} from "@/components/message.ts";
import {useTranslation} from "react-i18next";

type Props = {
	video?: VideoInfo;
	autoPlay?: boolean;
	onClose?: () => void
}
export default function VideoDetail({video, onClose,autoPlay}: Props) {
	const {t} = useTranslation()
	const [state, setState] = useSetState({
		exporting: false,
		pushing: false,
	})
	// 将视频推送到数字人直播间
	const pushToRoom = () => {
		if (video) {
			if (state.pushing) return
			setState({pushing: true})
			push2room([video.id]).then(() => {
				showToast(t('history.push_success'), 'success')
			}).catch(showErrorToast).finally(() => {
				setState({pushing: false})
			})
		}
	}
	// 下载视频
	const downloadVideo = () => {
		if (video?.oss_video_url) {
			const filename = video.oss_video_url.split('/').pop() || `${video.id}.flv`
			saveAs(video.oss_video_url, filename)
		}
	}

	return (<>
		<Modal
			open={!!video} width={390} closeIcon={null} title={null} footer={null} onCancel={onClose}
			rootClassName={"article-edit-modal"}
		>
			<div className="flex gap-2 px-6 pt-6">
				<div className="news-video w-[340px]">
					<div className="video-container bg-gray-100 rounded overflow-hidden">
						<Player autoPlay={autoPlay} url={video?.oss_video_url} poster={video?.cover} showControls={true}
						        className="w-[340px] h-[600px] bg-white"/>
					</div>
				</div>
			</div>
			<div className="flex justify-end modal-control-footer">
				<div className="flex gap-4">
					<button disabled={state.pushing} className="text-gray-400 hover:text-gray-800 " type="button" onClick={pushToRoom}>{t('video.push_to_live')}</button>
					<button disabled={state.exporting} className="text-gray-400 hover:text-gray-800 " onClick={downloadVideo}
					        type="button">{t('video.download')}
					</button>
					<button onClick={onClose} type="button" className="text-gray-800 hover:text-blue-500">{t('close')}</button>
				</div>
			</div>
		</Modal>
	</>)
}