import React, {useEffect, useMemo, useRef} from "react";
import {Checkbox, Popover} from "antd";
import {useBoolean, useClickAway} from "ahooks";
import {CaretUpOutlined} from "@ant-design/icons";
import {useTranslation} from "react-i18next";

type ValueType = Id[][];
type ValueFunc = (prev:ValueType)=>ValueType;
const TagSelect = (props: {
	options: OptionItem[];
	onChange: (values: Id[][]) => void;
	className?: string;
	defaultSelectTags?: Id[][];
}) => {
	const [selectValues, __setSelectValues] = React.useState<ValueType>([])
	const [checkedAll, _setCheckedAll] = React.useState<boolean>(false)
	const [visible, {set}] = useBoolean(false);
	const allValues = useMemo(()=>{
		const values:Id[][] = []
		props.options.forEach(item=>{
			if(item && item.children?.length){
				// eslint-disable-next-line no-unsafe-optional-chaining
				values.push(...(item.children?.map(c => [item.value, c.value])))
			}
		})
		return values
	},[props.options])
	const _setSelectValues = (values: (ValueType | ValueFunc)) => {
		if(typeof values == 'function'){
			__setSelectValues((prev)=>{
				const data = values(prev);
				props.onChange(data)
				return data
			})
		}else{
			__setSelectValues(values)
			props.onChange(values)
		}
	}
	const handleAllChanged = (checked: boolean) => {
		_setCheckedAll(checked)
		const values:Id[][] = []
		if (checked){
			// set(false)
			values.push(...allValues)
		}
		_setSelectValues(values)
	}
	const handleLevel1Change = (checked: boolean, item: OptionItem) => {
		console.log('handleLevel1Change', checked, item)
		if (checked) {
			const values = selectValues.filter(s => s[0] != item.value)
			const checkedIds: Id[][] = [];
			item.children?.forEach(c => {
				checkedIds.push([item.value, c.value])
			})
			const _values = [...values, ...checkedIds];
			_setCheckedAll(_values.length == allValues.length)
			_setSelectValues(_values)
		} else {
			_setCheckedAll(false)
			const values = selectValues.filter(s => s[0] != item.value)
			_setSelectValues([...values])
		}
	}
	const level1Checked = (item: OptionItem) => {
		// 完全没有选中
		if (selectValues.findIndex(s => s[0] == item.value) == -1) return -1
		const myList = selectValues.filter(s => s[0] == item.value)
		// 只有1个但是全选或者选中元素和子元素个数相等
		if (myList.length == item.children?.length) return 1;
		return 0;
	}
	const handleLevel2Change = (checked: boolean, item: OptionItem, parent: OptionItem) => {
		// 获取一级选项的选中状态
		const parentList = selectValues.filter(s => s[0] == parent.value)
		_setSelectValues((prev) => {
			let values = [...prev]
			if (checked) {
				values = [...prev,[parent.value, item.value]]
			} else {
				_setCheckedAll(false)
				if(parentList.length == 0){ //  && parentList[0].length == 1
					return prev;
				}
				values = values.filter(s => s.length == 1 || s[1] != item.value)
			}
			_setCheckedAll(values.length == allValues.length)
			return values
		})
	}
	const level2Checked = (item: OptionItem, parent: OptionItem) => {
		// 获取一级选项的选中状态
		const parentList = selectValues.filter(s => s[0] == parent.value)
		// 没有找到父级
		if (parentList.length == 0) return false;
		if (parentList.length == 1) {
			// 只有一个 且长度为0 说明是全选
			if (parentList[0].length == 1) return true;
			return parentList[0][1] == item.value;
		}

		return parentList.findIndex(s => s[1] == item.value) != -1;
	}
	const {t} = useTranslation()
	const ref = useRef<HTMLDivElement|null>(null)
	useClickAway(()=>{
		set(false)
	},ref)
	useEffect(()=>{
		if(props.defaultSelectTags){
			__setSelectValues(props.defaultSelectTags)
		}
		//console.log('props.defaultSelectTags',props.defaultSelectTags)
	},[props.defaultSelectTags])

	return (<div ref={ref} className={`tag-select-container z-10 select-none relative group ${props.className}`}>
			<div className="select-value w-[120px] flex justify-center items-center"
			     onClick={(e) => {
					 e.preventDefault();
					 e.stopPropagation();
				     set(!visible)
			     }}
			>
				<span>{checkedAll || selectValues.length == 0 ? t('news.news_all_source') : t('news.source')}</span>
				<CaretUpOutlined className={`ml-2 arrow-icon ${visible ? 'rotate-0' : 'rotate-180'}`}/>
			</div>
			<div className={`options-list-container absolute ${visible ? 'block' : 'hidden'}`}>
				<div className="inner">
				<ul className="options-list">
					<li className="select-option-item relative">
						<div className="option-value whitespace-nowrap flex justify-between">
							<span className="text-center flex-1"
							      onClick={() => handleAllChanged(!checkedAll)}>t('news.news_all_source')</span>
							<Checkbox className="ml-6" checked={checkedAll}
							          onChange={e => handleAllChanged(e.target.checked)}/>
						</div>
					</li>
					{props.options.filter(s => s.value != 999999).map((option) => {
						const checkStatus = level1Checked(option)
						return (<li key={option.value} className="select-option-item relative">
							{(option.children && option.children.length > 0) ?
								<Popover placement="rightTop" trigger={['hover']}
								         rootClassName="tag-select-child-container" arrow={false}
								         content={option.children && <ul className="sub-options-list select-none" onClick={(e)=>{
											 e.preventDefault();
											 e.stopPropagation()
								         }}>
									         {option.children.map((subOption) => {
										         const myCheckStatus = level2Checked(subOption, option)
										         return (<li key={subOption.value}
										                     className="sub-option-item select-option-item whitespace-nowrap">
											         <div
												         className="option-value whitespace-nowrap flex justify-between">
												         <span
													         onClick={() => {
														         handleLevel2Change(!myCheckStatus, subOption, option)
													         }}>{subOption.label}</span>
												         <Checkbox className="ml-6" checked={myCheckStatus}
												                   onChange={e => handleLevel2Change(e.target.checked, subOption, option)}/>
											         </div>
										         </li>)
									         })}
                                         </ul>}>
									<div className="option-value whitespace-nowrap flex justify-between">
										<span className="text-center flex-1" onClick={() => {
											handleLevel1Change(checkStatus == 1 ? false:true,  option)
										}}>{option.label}</span>
										<Checkbox className="ml-6"
										          checked={checkStatus == 1}
										          indeterminate={checkStatus == 0}
										          onChange={e => {
											          handleLevel1Change(e.target.checked, option)
										          }}/>
									</div>
								</Popover> : <div className="option-value whitespace-nowrap flex justify-between">
									<span>{option.label}</span>
								</div>
							}

						</li>)
					})}
				</ul>
				</div>
			</div>
		</div>
	)
}
export default TagSelect