import { styled } from 'styled-components';
import { useState, useEffect } from 'react';
import { TextInput, SelectInput, InputLabel, FormWrapper, BtnWrapper, ButtonClose } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import Modal from '../../components/common/modal/Modal';
import { UserView } from '../../apis';

const UserViewSearchBar = ({ setInfoView, handleTab, setResultData, resultData }) => {
	const [modalState, setModalState] = useState('hidden');
	const [form, setForm] = useState('');
	const [isNullValue, setIsNullValue] = useState(false);
	const [message, setMessage] = useState('필수값을 입력해주세요.');
	const [dataLength, setDataLength] = useState(false);
	const [dataList, setDataList] = useState([]);
	const [searchData, setSearchData] = useState({
		searchType: 'DEFAULT',
		searchKey: '',
	});

	// console.log(dataList)

	const searchType = [
		{ value: 'DEFAULT', name: '선택' },
		{ value: 'NAME', name: '아바타명' },
		{ value: 'GUID', name: 'GUID' },
		{ value: 'ACCOUNT', name: 'Account ID' },
		{ value: 'FRIEND_CODE', name: '친구코드' },
	];

	const fetchData = async (searchType, searchKey) => {
		const token = sessionStorage.getItem('token');
		setDataList(await UserView(token, searchType, searchKey));
	};

	useEffect(() => {
		dataList && setDataLength(Object.values(dataList).length);
	}, [dataList]);

	const handleSearch = (searchType, searchKey) => {
		fetchData(searchType, searchKey);
	};

	const handleReset = (e) => {
		e.preventDefault();

		setSearchData({
			searchType: 'DEFAULT',
			searchKey: '',
		});
		setInfoView('none');
		window.location.reload();
	};

	const handleRegistModalClose = (e) => {
		e.preventDefault();

		if (searchData.searchKey.length === 0 || searchData.searchType === 'DEFAULT') {
			setMessage(searchData.searchType === 'DEFAULT' ? '항목을 선택해주세요.' : '필수값을 입력해주세요.');
			setIsNullValue(true);
		} else if (searchData.searchKey && modalState === 'hidden') {
			setIsNullValue(false);

			handleSearch(searchData.searchType, searchData.searchKey);
			setModalState('view');
		} else {
			setModalState('hidden');
		}
	};

	const handleModal = () => {
		if (modalState === 'hidden') {
			setModalState('view');
		} else {
			setInfoView('flex');
			handleTab('기본정보');
			setModalState('hidden');
		}
	};

	const handleModalClose = () => {
		if (modalState === 'hidden') {
			setModalState('view');
		} else {
			setModalState('hidden');
		}
	};

	const handleGuid = data => {
		// setResultData(data.guid);
		setResultData(data);
		handleModal();
	};



	return (
		<>
			<FormWrapper onSubmit={e => handleRegistModalClose(e)}>
				<SearchbarStyle>
					<SearchItem>
						<InputLabel>유저 조회</InputLabel>
						<InputGroup>
							<SelectInput 
								value={searchData.searchType} 
								onChange={e => { setSearchData({ ...searchData, searchType: e.target.value }); setDataList([])}}
							>
								{searchType.map((data, index) => (
									<option key={index} value={data.value} disabled={data.value === 'FRIEND_CODE' ? true : false}>
										{data.name}
									</option>
								))}
							</SelectInput>
							<TextInput
								type="text"
								width="300px"
								value={searchData.searchKey}
								onChange={e => setSearchData({ ...searchData, searchKey: e.target.value })}
								disabled={searchData.searchType === 'DEFAULT' ? true : false}
							/>
						</InputGroup>
					</SearchItem>
					<BtnWrapper $gap="8px">
						<Button type="button" theme="reset" handleClick={e => handleReset(e)} />
						<Button type="button"
							theme="search" text="검색" 
							handleClick={e => handleRegistModalClose(e)}
						/>
						{isNullValue && <SearchBarAlert>{message}</SearchBarAlert>}
					</BtnWrapper>
				</SearchbarStyle>
			</FormWrapper>
			<Modal $view={modalState} $bgcolor="transparent" min="600px">
				<BtnWrapper $justify="space-between">
					<PopTitle className="title">검색 대상 선택</PopTitle>
					<ButtonClose onClick={handleModalClose} />
				</BtnWrapper>
				<PopCategory>{searchType.map(data => data.value === searchData.searchType && data.name)}</PopCategory>
				<PopResult>
					
					{dataLength === 0 ? (
						<ResultItem>일치하는 조회 대상이 없습니다.</ResultItem>
					) : searchData.searchType === 'NAME' ? (
						<ResultItem onClick={() => handleGuid(dataList)}>{dataList.nickname && dataList.nickname}</ResultItem>
					) : (
						<ResultItem onClick={() => handleGuid(dataList)}>{dataList.guid && dataList.guid}</ResultItem>
					)}
				</PopResult>
			</Modal>
		</>
	);
};

export default UserViewSearchBar;

const SearchbarStyle = styled.div`
	width: 100%;
	display: flex;
	flex-wrap: wrap;
	gap: 20px 0;
	font-size: 14px;
	padding: 20px;
	border-top: 1px solid #000;
	border-bottom: 1px solid #000;
	margin-bottom: 40px;
`;

const SearchItem = styled.div`
	display: flex;
	align-items: center;
	gap: 20px;
	margin-right: 50px;

	${TextInput}, ${SelectInput} {
		height: 35px;
	}
	${TextInput} {
		padding: 0 10px;
		max-width: 400px;
	}
`;

const InputGroup = styled.div`
	display: flex;
	align-items: center;
	gap: 5px;
`;

const PopTitle = styled.div`
	font-weight: 700;
	margin-bottom: 10px;
	font-size: 18px;
`;
const PopCategory = styled.div`
	background: #818181;
	color: #fff;
	font-size: 16px;
	font-weight: 700;
	padding: 5px 10px;
`;
const PopResult = styled.div`
	border-bottom: 1px solid #000;
`;
const ResultItem = styled.div`
	padding: 4px 10px;
	cursor: pointer;
	&:hover {
		background: #f6f6f6;
	}
`;

const SearchBarAlert = styled.div`
	width: 100%;
	color: #d60000;
	margin: auto;
	padding-left: 15px;
`;
