import {Input} from "antd";
import {SearchOutlined} from "@ant-design/icons";
import React, {useEffect, useState} from "react";
import {useSetState} from "ahooks";
import useArticleTags from "@/hooks/useArticleTags.ts";
import TagSelect from "@/components/form/tag-select.tsx";
import {useTranslation} from "react-i18next";

export default function EditSearchForm(props: {
	onSubmit: (values: ApiArticleSearchParams) => void;
	defaultParams?: Partial<ApiArticleSearchParams>;
}) {
	const {t} = useTranslation()
	const articleTags = useArticleTags()
	const [tags, _setTags] = useState<Id[][]>([]);
	const [prevSearchName, setPrevSearchName] = useState<string>(props.defaultParams?.title || '')
	const [params, setParams] = useSetState<ApiArticleSearchParams>({
		pagination: {limit: 10, page: 1},
		title: props.defaultParams?.title || ''
	});

	const handleSubmit = (_tags?: Id[][], from?: 'input') => {
		if (from == 'input' && (params.title == prevSearchName || (!params.title && !prevSearchName))) return
		params.title = prevSearchName;
		setParams({title: prevSearchName})
		const __tags = _tags || tags;
		params.tags = __tags.length == 0 ? undefined : __tags.map(it => {
			if (Array.isArray(it)) {
				return {
					level1: it[0],
					level2: it.length == 2 ? it[1] : 0
				}
			} else {
				return {
					level1: it, level2: 0
				}
			}
		});
		props.onSubmit({
			...params,
			pagination: {
				page: 1,
				limit: 10
			}
		})
	}
	useEffect(() => {
		const {defaultParams} = props;
		if (!defaultParams) {
			return;
		}
		const tags: Id[][] = []

		if (defaultParams.tags) {
			defaultParams.tags.forEach(it => {
				tags.push([it.level1, it.level2])
			})
			_setTags(tags)
		}
	}, [articleTags])
	const setTags = (_tags: Id[][]) => {
		console.log(_tags)

		_setTags(_tags)
		handleSubmit(_tags)
	}

	return (
		<div className="search-form-input flex gap-2 items-center">
			<Input
				value={prevSearchName}
				onChange={e => setPrevSearchName(e.target.value)}
				type="text" className="rounded-3xl px-3 w-[270px]"
				prefix={<SearchOutlined/>}
				placeholder={t('news.edit_form_search')}
				onPressEnter={() => handleSubmit(undefined, 'input')}
				onBlur={() => handleSubmit(undefined, 'input')}
			/>
			{/*<span className="ml-5 text-sm">来源</span>*/}
			{/*<ArticleCascader*/}
			{/*	options={articleTags}*/}
			{/*	onChange={setTags}*/}
			{/*/>*/}
			<TagSelect defaultSelectTags={tags} onChange={setTags} options={articleTags}/>
		</div>
	)
}