import {Checkbox, Empty, Space} from "antd";
import React, {useEffect, useMemo, useRef, useState} from "react";
import {DndContext} from "@dnd-kit/core";
import {arrayMove, SortableContext} from "@dnd-kit/sortable";
import {useSetState} from "ahooks";

import {VideoListItem} from "@/components/video/video-list-item.tsx";
import ArticleEditModal from "@/components/article/edit-modal.tsx";
import {deleteFromList, getList, modifyOrder, VideoStatus} from "@/service/api/video.ts";
import {formatDuration} from "@/util/strings.ts";
import ButtonBatch from "@/components/button-batch.tsx";
import {showErrorToast, showToast} from "@/components/message.ts";
import {Player, PlayerInstance} from "@/components/video/player.tsx";
import ButtonPush2Room from "@/pages/video/components/button-push2room.tsx";
import ButtonToTop from "@/components/scoller/button-to-top.tsx";
import InfiniteScroller, {InfiniteScrollerRef} from "@/components/scoller/infinite-scroller.tsx";
import {IconDelete} from "@/components/icons";
import {useLocation} from "react-router-dom";
import {useTranslation} from "react-i18next";

export default function VideoIndex() {
	const {t} = useTranslation()
	const [editId, setEditId] = useState(-1)
	const loc = useLocation()
	const [videoData, setVideoData] = useState<VideoInfo[]>([])
	const player = useRef<PlayerInstance | null>(null)
	const scrollerRef = useRef<InfiniteScrollerRef | null>(null)
	const [state, setState] = useSetState({
		checkedAll: false,
		playingIndex: -1,
		showToTop: false,
		showStatePos: false,
		playState: {
			current: -1,
			total: -1
		},
		loading:false
	})
	const [checkedIdArray, setCheckedIdArray] = useState<Id[]>([])
	const [refreshTimer,setTimer] = useState(0)

	// 加载列表
	const loadList = (needReset = true) => {
		if(state.loading) return;
		if(refreshTimer) {
			clearTimeout(refreshTimer)
			setTimer(0)
		}
		setState({loading: true})
		getList().then((ret) => {
			const list = ret.list || []
			setVideoData(list)
			if (needReset) {
				setCheckedIdArray([])
				setState({checkedAll: false, playingIndex: -1})
			}
			// 判断是否有生成中的视频
			if (list.filter(s => s.status == VideoStatus.Generating).length > 0) {
				// 每5s重新获取一次最新数据
				setTimer(()=>setTimeout(() => loadList(false), 5000) as any);
			}
		}).catch(showErrorToast)
			.finally(()=>{
			setState({loading: false})
		})
		return ()=>{
			if(refreshTimer){

				clearTimeout(refreshTimer)
			}
			console.log('go out',refreshTimer)
		}
	}

	// 播放视频
	const playVideo = (video: VideoInfo, playingIndex: number) => {
		if (state.playingIndex == playingIndex) {
			player.current?.pause();
			setState({playingIndex: -1})
			return;
		}
		if (video.status == VideoStatus.Generating) return;
		// setState({playingIndex})
		// player.current?.play('https://staticplus.gachafun.com/ai-collect/composite_video/2024-12-17/1186196465916190720.flv', 30)
		//
		if (video.oss_video_url && video.status !== 1) {
			setState({playingIndex})
			player.current?.play(video.oss_video_url, 0)
		}
	}
	// 处理全选
	const handleAllCheckedChange = () => {
		setCheckedIdArray(state.checkedAll ? [] : videoData.map(v => v.id))
		setState({
			checkedAll: !state.checkedAll
		})
	}
	const handleModifySort = (items: VideoInfo[]) => {

		modifyOrder(items.map(s => s.id)).then(() => {
			showToast(t('video.sort_modify_success'), 'success')
		}).catch(() => {
			loadList();
			showToast(t('video.sort_modify_failed'), 'warning')
		})

		return ()=>{
			try{
				Array.from(document.querySelectorAll('video')).forEach(v => v.pause())
			}catch (e){
				console.log(e)
			}
		}
	}
	//
	useEffect(loadList, [])
	const totalDuration = useMemo(() => {
		if (!videoData || videoData.length == 0) return 0;
		if (state.playingIndex == -1 || state.playingIndex >= videoData.length) return 0
		const v = videoData[state.playingIndex] as VideoInfo;
		return Math.ceil(v.duration / 1000)
		// 计算总时长
		//return videoData.reduce((sum, v) => sum + Math.ceil(v.duration / 1000), 0);
	}, [videoData, state.playingIndex])

	useEffect(() => {
		if (loc.state == 'push-success' && !state.showStatePos && videoData.length && scrollerRef.current) {
			const generatingItem = document.querySelector(`.list-item-state-${VideoStatus.Generating}`)
			if (generatingItem) {
				generatingItem.scrollIntoView({behavior: 'smooth'})
				setState({showStatePos: true})
			}
		}
	}, [videoData, scrollerRef])
	const processDeleteVideo = async (ids: Id[]) => {
		deleteFromList(ids).then(() => {
			showToast(t('delete_success'), 'success')
			loadList()
		}).catch(showErrorToast)
	}

	return (<div className="container py-5 page-live">
		<div className="h-[36px]"></div>
		<div className="flex">
			<div className="video-player-container mr-16 w-[360px] flex items-center">
				<div>
					<div className="text-center text-base text-gray-400">{t("generating.title")}</div>
					<div className="video-player flex items-center mt-2">
						<div className=" w-[360px] h-[636px] rounded overflow-hidden">
							<Player
								ref={player} url={videoData[state.playingIndex]?.oss_video_url}
								onChange={(state) => {
									console.log(state)
									if (state.end || state.error) setState({playingIndex: -1})
								}}
								onProgress={(current, duration) => {
									setState({
										playState: {
											current: current,
											total: duration
										}
									})
								}}
								className="w-[360px] h-[640px] bg-white"/>
						</div>
					</div>
					<div className="text-center text-sm mt-4 text-gray-400">{formatDuration(state.playState.current)} / {formatDuration(state.playState.total)}</div>
				</div>
			</div>
			<div className="video-list-container rounded mt-2 flex flex-col flex-1">
				<div className="live-control flex justify-between">
					<div className="pl-[70px]"></div>
					<div className="flex items-center">
						<Space>
							<span>{t('select.selected_some',{count:videoData.length || 0})}</span>
							<span className={'text-blue-500'}>{t('select.selected_some',{count:checkedIdArray.length})}</span>
						</Space>
						<button className="hover:text-blue-300 text-gray-400 ml-2"
						        onClick={handleAllCheckedChange}>
							<span className="text-sm mr-2">{t("select.select_all")}</span>
							{/*<CheckCircleFilled className={clsx({'text-blue-500': state.checkedAll})}/>*/}
						</button>
						<Checkbox checked={state.checkedAll} onChange={() => handleAllCheckedChange()}/>
					</div>
				</div>
				<div className={'video-list-sort-container flex-1 mt-1'}>
					<div className="list-header">
						<div className="list-row header-row">
							<div className="col number">No.</div>
							<div className="col cover">{t('video.title_thumb')}</div>
							<div className="col title">{t('video.title')}</div>
							<div className="col generated-time">{t('video.title_generated_time')}</div>
							<div className="col operation">{t('video.title_operation')}</div>
						</div>
					</div>
					<InfiniteScroller loading={state.loading} ref={scrollerRef} onScroll={top => setState({showToTop: top > 30})}>
						{
							videoData.length == 0 ? <div className="m-auto py-16"><Empty/></div> :
								<div className="sort-list-container flex-1">
									<DndContext onDragEnd={(e) => {
										const {active, over} = e;
										if (over && active.id !== over.id) {
											let oldIndex = -1, newIndex = -1;
											const originArr = [...videoData]
											console.log(originArr.map(s => s.id))
											setVideoData((items) => {
												oldIndex = items.findIndex(s => s.id == active.id);
												newIndex = items.findIndex(s => s.id == over.id);
												const newSorts = arrayMove(items, oldIndex, newIndex);
												handleModifySort(newSorts)
												return newSorts;
											});
											// modal.confirm({
											// 	title: '提示',
											// 	content: '是否要移动到指定位置',
											// 	onOk: handleModifySort,
											// 	onCancel: () => {
											// 		setVideoData(originArr);
											// 	}
											// })
										}
									}}>
										<SortableContext items={videoData}>
											{videoData.map((v, index) => (
												<VideoListItem
													video={v}
													index={index + 1}
													id={v.id}
													key={index}
													type={'create'}
													active={checkedIdArray.includes(v.id)}
													playing={state.playingIndex == index}
													checked={checkedIdArray.includes(v.id)}
													className={`list-item-${index} mt-3 mb-2 list-item-state-${v.status}`}
													onCheckedChange={(checked) => {
														setCheckedIdArray(idArray => {
															const newArr = checked ? idArray.concat(v.id) : idArray.filter(id => id != v.id);
															setState({checkedAll: newArr.length == videoData.length})
															return newArr;
														})
													}}
													onItemClick={() => playVideo(v, index)}
													onRemove={() => processDeleteVideo([v.id])}
													onEdit={v.status == VideoStatus.Generating ? undefined : () => {
														setEditId(v.article_id)
													}}
													editable={v.status != VideoStatus.Generating}
													sortable={v.status != VideoStatus.Generating}
												/>))}
										</SortableContext>
									</DndContext>
								</div>
						}
						<div className="h-[100px]"></div>
					</InfiniteScroller>
				</div>
			</div>
			<div className="page-action">
				<ButtonToTop visible={state.showToTop} onClick={() => scrollerRef.current?.scrollToPosition(0)}/>
				{checkedIdArray.length > 0 && <ButtonBatch
                    onProcess={deleteFromList}
                    selected={checkedIdArray}
                    emptyMessage={t('video.delete_empty')}
                    title={t('video.delete_description',{count:checkedIdArray.length})}
                    className='bg-gray-300 hover:bg-gray-400 text-white'
                    confirmMessage={t('video.delete_confirm')}
                    onSuccess={() => {
						showToast(t('delete_success'), 'success')
						loadList()
					}}
                >
                    <span className="text">{t('delete_batch')}</span>
                    <IconDelete/>
                </ButtonBatch>}
				<ButtonPush2Room ids={checkedIdArray} list={videoData} onSuccess={loadList}/>
			</div>
		</div>
		<ArticleEditModal type={'video'} id={editId} onClose={() => setEditId(-1)}/>
	</div>)
}