import React, {useEffect, useRef, useState} from "react";
import {Checkbox, Modal, Space} from "antd";
import {useRequest, useSetState} from "ahooks";

import VideoItem from "@/pages/library/components/video-item.tsx";
import SearchForm from "@/pages/library/components/search-form.tsx";
import VideoDetail from "@/pages/library/components/video-detail.tsx";
import {deleteHistories, push2room, search} from "@/service/api/video.ts";
import {getList} from "@/service/api/live.ts";
import InfiniteScroller, {InfiniteScrollerRef} from "@/components/scoller/infinite-scroller.tsx";
import ButtonBatch from "@/components/button-batch.tsx";
import ButtonToTop from "@/components/scoller/button-to-top.tsx";
import {IconArrowRight, IconDelete} from "@/components/icons";
import {useTranslation} from "react-i18next";

const DEFAULT_PAGE_LIMIT = {
	page: 1,
	limit: 12
}
export default function LibraryIndex() {
	const {t} = useTranslation()
	const [modal, contextHolder] = Modal.useModal();
	const [checkedIdArray, setCheckedIdArray] = useState<number[]>([])
	const [params, setParams] = useState<VideoSearchParams>({
		time_flag: 0,
		pagination: {...DEFAULT_PAGE_LIMIT}
	})
	const [state, setState] = useSetState({
		checkedAll: false,
		loading: false,
		pushedCount: 0,
		showToTop: false
	})
	const [data, setData] = useState<DataList<VideoInfo>>()
	const scrollerRef = useRef<InfiniteScrollerRef | null>(null)

	const {loading} = useRequest(() => search(params), {
		refreshDeps: [params],
		onSuccess: (data) => {
			setData(prev => {
				// 判断页码是否是第1页
				if (data.pagination.page == 1) return data;
				return {
					list: [...(prev?.list || []), ...(data?.list || [])],
					pagination: data.pagination
				}
			})
		}
	})

	const handleRemove = (video: VideoInfo) => {
		modal.confirm({
			title: t('confirm.title'),
			content: t('history.delete_confirm'),
			onOk: () => {
				console.log('OK', video);
			}
		})
	}
	const handleLive = async () => {
		if (checkedIdArray.length == 0) return;
		modal.confirm({
			title: t('confirm.push_title'),
			content: t('confirm.push_video'),
			onOk: () => {
				console.log('OK');
			}
		})
	}
	const [detailVideo, setDetailVideo] = useState<{
		video: VideoInfo,
		autoPlay: boolean
	}>()
	const handleAllCheckedChange = (checked: boolean) => {
		if (!data) return;
		setCheckedIdArray(checked ? data.list.map(v => v.id) : [])
		setState({
			checkedAll: !state.checkedAll
		})
	}
	const loadPushedState = () => {
		getList().then((ret) => {
			if (ret.list) {
				setState({pushedCount: ret.list.length})
			}
		})
	}
	const refresh = () => {
		loadPushedState();
		setParams(prev => ({...prev, pagination: {page: 1, limit: DEFAULT_PAGE_LIMIT.limit}, request_time: Date.now()}))
	}

	useEffect(loadPushedState, [])

	return (<>
		<div className={'container pb-5'}>
			{contextHolder}
			<div className="search-form-container">
				<SearchForm
					onSearch={setParams}
					onBtnStartClick={handleLive}
					loading={loading}
				/>
			</div>
			<div className="">
				<div className="live-control flex justify-between mb-2">
					<div className="pl-[70px]"></div>
					<div className="flex items-center">
						<Space className="text-gray-400" size={20}>
							<span>{t('select.total',{count:data?.list?.length || 0})}</span>
							<span>{t('select.pushed',{count:state.pushedCount})}</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-4"
						        onClick={() => handleAllCheckedChange(checkedIdArray.length != data?.list.length)}>
							<span className="text-sm mr-2">{t("select.select_all")}</span>
							{/*<CheckCircleFilled className={clsx({'text-blue-500': state.checkedAll})}/>*/}
						</button>
						<Checkbox checked={checkedIdArray.length == data?.list?.length}
						          onChange={e => handleAllCheckedChange(e.target.checked)}/>
					</div>
				</div>
				<InfiniteScroller
					ref={scrollerRef} loading={loading} rootClassName="video-history-list-container"
					pagination={data?.pagination} onCallback={(page) => {
					setParams(prev => ({
						...prev,
						pagination: {page, limit: DEFAULT_PAGE_LIMIT.limit}
					}))
				}} onScroll={(top) => setState({showToTop: top > 30})}
				>
					<div className={'video-list-container grid gap-4 grid-cols-3 xl:grid-cols-4'}>
						{data?.list?.map((it, idx) => (
							<VideoItem
								onLive={idx == 2}
								key={idx}
								videoInfo={it}
								onRemove={() => handleRemove(it)}
								onClick={(autoPlay) => setDetailVideo({video: it, autoPlay})}
								checked={checkedIdArray.includes(it.id)}
								onCheckedChange={(checked) => {
									setCheckedIdArray(idArray => {
										return checked ? idArray.concat(it.id) : idArray.filter(id => id != it.id);
									})
								}}
							/>
						))}
					</div>
				</InfiniteScroller>
			</div>
		</div>
		{detailVideo && <VideoDetail video={detailVideo.video} autoPlay={detailVideo.autoPlay}
                                     onClose={() => setDetailVideo(undefined)}/>}

		<div className="page-action">
			<ButtonToTop visible={state.showToTop} onClick={() => scrollerRef.current?.scrollToPosition(0)}/>
			{checkedIdArray?.length > 0 && <ButtonBatch
				selected={checkedIdArray}
				onSuccess={refresh}
                className='bg-gray-300 hover:bg-gray-400 text-white'
				icon={<IconDelete className=""/>}
				title={t('video.delete_description',{count:checkedIdArray.length})}
				emptyMessage={t('video.delete_empty')}
				confirmMessage={<span dangerouslySetInnerHTML={{__html:t('video.delete_confirm')}}></span>}
				onProcess={deleteHistories}
			>{t('delete_batch')}</ButtonBatch>}
			{checkedIdArray?.length > 0 && <ButtonBatch
				selected={checkedIdArray}
				onSuccess={refresh}
				className='bg-[#4096ff] hover:bg-blue-600 text-white'
				icon={<IconArrowRight className={'text-white'}/>}
				onProcess={push2room}
				emptyMessage={t('video.push_empty')}
			>{t('video.push_to_live')}</ButtonBatch>}
		</div>
	</>)
}