import React, {useMemo, useRef, useState} from "react";
import {Checkbox, Divider, Empty, Modal, Space} from "antd";
import {useRequest} from "ahooks";
import {CloseOutlined} from "@ant-design/icons"
import {clsx} from "clsx";

import SearchPanel from "@/pages/news/components/search-panel.tsx";
import {getById, getList} from "@/service/api/news.ts";
import {showLoading} from "@/components/message.ts";
import {formatTime} from "@/util/strings.ts";
import ButtonPushNews2Article from "@/pages/news/components/button-push-news2article.tsx";
import ButtonNewsDownload from "@/pages/news/components/button-news-download.tsx";
import InfiniteScroller, {InfiniteScrollerRef} from "@/components/scoller/infinite-scroller.tsx";
import ButtonToTop from "@/components/scoller/button-to-top.tsx";
import {useIndexArrayCache} from "@/hooks/useCache.ts";
import {useTranslation} from "react-i18next";

const FilterCache: Partial<ApiArticleSearchParams> = {
	time_flag: 1,
}
export default function NewsIndex() {
	const {t} = useTranslation()
	const [params, setParams] = useState<ApiArticleSearchParams>({
		pagination: {page: 1, limit: 12}, 
		...FilterCache
	})

	// const [checkedId, setCheckedId] = useState<Id[]>([])
	const {cache: checkedId, set: setCheckedId} = useIndexArrayCache()

	const [activeNews, setActiveNews] = useState<NewsInfo>()

	const [state, setState] = useState<{
		checkAll?: boolean;
		showToTop?: boolean;
	}>({})

	const [data, setData] = useState<DataList<ListCrawlerNewsItem>>();
	const {loading} = useRequest(() => getList(params), {
		refreshDeps: [params],
		onSuccess: (_data) => {
			FilterCache.tag_level_1_id = params.tag_level_1_id;
			FilterCache.tag_level_2_id = params.tag_level_2_id;
			FilterCache.title = params.title;
			FilterCache.time_flag = params.time_flag;
			console.log('success',FilterCache)
			if (params.pagination.page === 1) {
				setData(_data)
				setState({checkAll: checkedId && _data.list && checkedId.length === _data.list.length})
			} else {
				setData({
					pagination: _data.pagination,
					list: [...(data?.list || []), ..._data.list]
				})
			}
		}
	})

	const handleViewNewsDetail = (id: number) => {
		const {update, close} = showLoading(`${t('news.get_detail')}...`)
		getById(id).then(res => {
			close()
			setActiveNews({...res, id})
		}).catch(() => {
			update(t('news.get_detail_error'), 'info')
		})
	}

	const currentEnabledList = useMemo(() => {
		if (data?.list && data?.list?.length > 0) {
			return data.list.filter(s => s.internal_article_id == 0)
		}
		return [];
	}, [data?.list])
	const handleCheckAll = (checked: boolean) => {
		setState({checkAll: checked})
		if (checked) {
			setCheckedId(currentEnabledList.map(item => item.id) || [])
		} else {
			setCheckedId([])
		}
	}
	const scrollerRef = useRef<InfiniteScrollerRef | null>(null)
	const handleCheckChange = (id: number) => {
		if (checkedId.includes(id)) {
			setCheckedId(checkedId.filter(id => id != id))
		} else {
			setCheckedId([...checkedId, id])
		}
	}
	return (<div className={'container pb-5'}>
		<SearchPanel defaultParams={params} onSearch={setParams}/>
		{activeNews && <Modal
            rootClassName={'news-detail-modal'}
            closeIcon={null} open={true} width={1000}
            footer={null} onCancel={() => setActiveNews(undefined)}
        >
            <div className="news-detail pl-16 pr-1 flex pb-5">
                <div className="px-4 py-6 bg-white flex-1">
                    <div className="new-title text-2xl">{activeNews?.title}</div>
                    <div className="info mt-2 mb-2 text-sm flex gap-3">
                        <span className="source text-blue-400">{activeNews?.media_name}</span>
                        <span className="create-time text-gray-400">{formatTime(activeNews?.publish_time)}</span>
                    </div>
                    <Divider className={'my-2'}/>
                    <div className="overflow-auto leading-7 text-base news-detail-content-container"
                         style={{maxHeight: 500}} dangerouslySetInnerHTML={{__html: activeNews?.content || ''}}></div>
                </div>
                <div className="actions ml-3">
                    <div className="close">
                        <CloseOutlined className="text-xl text-gray-400 hover:text-gray-800"
                                       onClick={() => setActiveNews(undefined)}/>
                    </div>
                    <div className="whitespace-nowrap text-sm mt-2">
                        <Checkbox
                            checked={checkedId.includes(activeNews!.id)}
                            onChange={() => handleCheckChange(activeNews!.id)}
                        ><span className="ml-[-4px]">{t('select.text')}</span></Checkbox>
                    </div>
                </div>
            </div>
        </Modal>}
		<div className="news-list-container">
			<div className="controls flex justify-end mb-3 gap-5">
				<Space size={20}>
					<span>{t('select.total',{count:data?.list?.length || 0})}</span>
					<span className={'text-blue-500'}>{t('select.selected_some',{count:checkedId.length})}</span>
				</Space>
				<div>
					<span className={'inline-block cursor-pointer mr-2'} onClick={() => {
						handleCheckAll(!state.checkAll)
					}}>{t('select.select_all')}</span>
					<Checkbox checked={state.checkAll && checkedId.length == currentEnabledList.length} onChange={e => {
						handleCheckAll(e.target.checked)
					}}></Checkbox>
				</div>
			</div>
			<InfiniteScroller
				className="grid grid-cols-2 gap-4 xl:grid-cols-4 md:grid-cols-3 pb-2"
				pagination={data?.pagination}
				loading={loading}
				ref={scrollerRef}
				onScroll={(top) => setState({showToTop: top > 30})}
				onCallback={(page) => {
					setParams({...params, pagination: {...params.pagination, page}})
				}}
				empty={<Empty/>}
			>
				{data?.list?.map(item => (
					<div key={item.id}
					     className={clsx(`p-4 flex items-start group rounded border border-transparent`, {
						     'bg-news-to-edit': item.internal_article_id > 0,
						     'bg-white': !item.internal_article_id && !checkedId.includes(item.id),
						     'bg-blue-500/20 border-[#d9eaff]': checkedId.includes(item.id)
					     })}>

						<div className="news-content flex-1">
							<div className="title h-[60px] line-clamp-2 text-lg cursor-pointer hover:text-blue-500"
							     onClick={() => {
								     handleViewNewsDetail(item.id)
							     }}>{item.title}</div>
							<div className="content flex gap-3 mt-2 mb-3">
								<div
									className="text text-gray-600 text-sm h-[70px] line-clamp-3 overflow-hidden text-ellipsis text-justify leading-6 flex-1 text-justify break-all text-wrap">
									{item.summary}
								</div>
								{item.cover && <div
                                    className="cover border border-gray-100 flex items-center rounded overflow-hidden"
                                    style={{width: 100, height: 70}}>
                                    <img className="w-full h-full object-cover" src={item.cover}/>
                                </div>}
							</div>
							<div className="info text-gray-400 mt-4 text-sm">
								<div className="line-clamp-1">{t('news.source')}: <span>{item.data_source_name}</span></div>
								<div className="extras flex items-center justify-between gap-3">
									<div><span>{formatTime(item.publish_time, 'min')}</span></div>
									<div><span>{t('news.image_count')}: {item.img_num}</span></div>
									<div><span>{t('news.word_count')}: {item.content_word_count}</span></div>
									<div
										className={` mt-1`}>
										{item.internal_article_id > 0 ?
											<span className={"inline-block text-gray-600"}>{t('news.pushed')}</span> :
											<Checkbox checked={checkedId.includes(item.id)} onChange={() => {
												handleCheckChange(item.id)
											}}/>}
									</div>
								</div>
							</div>
						</div>
					</div>
				))}
			</InfiniteScroller>


		</div>
		<div className="page-action">
			<ButtonToTop visible={state.showToTop} onClick={() => scrollerRef.current?.scrollToPosition(0)}/>
			<div>
				<ButtonNewsDownload ids={checkedId}/>
			</div>
			<div>
				<ButtonPushNews2Article ids={checkedId}/>
			</div>

		</div>
	</div>)
}