import {Checkbox, Popconfirm, Space} from "antd";

import React, {useRef, useState} from "react";
import {useRequest} from "ahooks";
import {formatTime} from "@/util/strings.ts";
import ArticleEditModal from "@/components/article/edit-modal.tsx";
import {deleteByIds, getList} from "@/service/api/article.ts";
import EditSearchForm from "@/pages/news/components/edit-search-form.tsx";
import ButtonPush2Video from "@/pages/news/components/button-push2video.tsx";

import styles from './components/style.module.scss'
import InfiniteScroller, {InfiniteScrollerRef} from "@/components/scoller/infinite-scroller.tsx";
import {IconDelete, IconEdit, IconWarningCircle} from "@/components/icons";
import {clsx} from "clsx";
import ButtonToTop from "@/components/scoller/button-to-top.tsx";
import ButtonDeleteBatch from "@/pages/news/components/button-delete-batch.tsx";
import {showErrorToast, showToast} from "@/components/message.ts";
import {useTranslation} from "react-i18next";

const FilterCache: Partial<ApiArticleSearchParams> = {
	tags: [],
}
export default function NewEdit() {
	const {t} = useTranslation()
	const [state, setState] = useState<{
		checkAll?: boolean;
		showToTop?: boolean;
	}>({})
	const [editId, setEditId] = useState(-1)
	const [selectedRowKeys, setSelectedRowKeys] = useState<Id[]>([])

	const [params, setParams] = useState<ApiArticleSearchParams>({
		pagination: {page: 1, limit: 10},
		...FilterCache
	})
	const [data, setData] = useState<DataList<ListArticleItem>>()
	const {refresh, loading} = useRequest(() => getList(params), {
		refreshDeps: [params],
		onSuccess: (data) => {
			FilterCache.title = params.title;
			FilterCache.tags = params.tags;
			setData(prev => {
				// 判断页码是否是第1页
				if (data.pagination.page == 1) return data;
				return {
					list: [...(prev?.list || []), ...(data?.list || [])],
					pagination: data.pagination
				}
			})
		}
	})

	const handleItemChecked = (checked: boolean, item: ListArticleItem) => {
		if (checked) {
			setSelectedRowKeys(prev => [...prev, item.id])
		} else {
			setSelectedRowKeys(prev => prev.filter(it => it != item.id))
		}
	}
	const handleCheckAll = (checked: boolean) => {
		setState({checkAll: checked})
		if(!data?.list) return;
		if (checked) {
			setSelectedRowKeys(data?.list?.map(item => item.id) || [])
		} else {
			setSelectedRowKeys([])
		}
	}
	const scrollerRef = useRef<InfiniteScrollerRef | null>(null)
	const handleDelete = (id) => {
		deleteByIds([id]).then(() => {
			refresh()
			showToast(t('delete_success'), 'success')
		}).catch(showErrorToast)
	}

	return (<div className="container pb-5 news-edit">
		<div className="search-panel-container my-5">
			<div className="search-form flex pt-1 gap-5 justify-between">
				<EditSearchForm defaultParams={params} onSubmit={setParams}/>
				{/*<Button type="primary" onClick={() => setEditId(0)}>手动新增</Button>*/}
			</div>

			<div className="news-list-container mt-2">
				<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:selectedRowKeys.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 && (!data?.list || selectedRowKeys.length == data?.list?.length)}
						          onChange={e => {
							          handleCheckAll(e.target.checked)
						          }}/>
					</div>
				</div>
				<div className={styles.newListTable}>
					<div className="header row flex">
						<div className="col title">{t('news.title')}</div>
						<div className="col source">{t('news.source')}</div>
						<div className="col count-picture">{t('news.title_image_count')}</div>
						<div className="col count-words">{t('news.title_word_count')}</div>
						<div className="col time">{t('news.title_time')}</div>
						<div className="col operations">{t('news.title_operate')}</div>
					</div>
					<InfiniteScroller ref={scrollerRef} onCallback={(page) => {
						setParams(prev => ({
							...prev,
							pagination: {page, limit: 10}
						}))
					}} onScroll={(top) => setState({showToTop: top > 30})} loading={loading}
					                  pagination={data?.pagination}>
						<div className="body">
							{data?.list?.map((item, i) => {
								const checked = selectedRowKeys.includes(item.id)
								return <div key={i} className={clsx("row flex", {checked})}>
									<div className="col title cursor-pointer" onClick={() => setEditId(item.id)}>
										<div>
											<div className="text-base">{item.title}</div>
											<div
												className="summary text-xs text-gray-400 line-clamp-1">{item.summary}</div>
										</div>
									</div>
									<div className="col source">
										<div className="text-sm line-clamp-1">{item.media_name}-{item.column_name}</div>
									</div>
									<div className="col count-picture">
										<div className="text-sm">{item.img_num}</div>
									</div>
									<div className="col count-words">
										<div className="text-sm">{item.content_word_count}</div>
									</div>
									<div className="col time">
										<div
											className="text-sm">{formatTime(item.publish_time, 'YYYY-MM-DD HH:mm')}</div>
									</div>
									<div className="col operations">
										<span className="icon-btn" onClick={()=>setEditId(item.id)}><IconEdit/></span>
										<Popconfirm
											rootClassName={'popconfirm-main'}
											placement={'left'}
											arrow={false}
											icon={<IconWarningCircle/>}
											title={t('news.delete_confirm')}
											description={<span dangerouslySetInnerHTML={{__html:t('news.delete_description')}}></span>}
											onConfirm={() => {
												handleDelete(item.id)
											}}
										>
											<span className="icon-btn"><IconDelete/></span>
										</Popconfirm>
										<Checkbox checked={checked}
										          onChange={e => handleItemChecked(e.target.checked, item)}/>
									</div>
								</div>
							})}
						</div>
					</InfiniteScroller>
				</div>

				<div className="page-action">
					<ButtonToTop visible={state.showToTop} onClick={() => scrollerRef.current?.scrollToPosition(0)}/>
					{selectedRowKeys?.length > 0 && <ButtonDeleteBatch ids={selectedRowKeys} onSuccess={refresh}/>}
					<ButtonPush2Video ids={selectedRowKeys} onSuccess={refresh}/>
				</div>
			</div>
			<ArticleEditModal
				type="news"
				id={editId}
				onClose={(saved) => {
					setEditId(-1)
					if (saved) refresh()
				}}/>
		</div>
	</div>)
}