import { useEffect, useState } from 'react';
import { styled } from 'styled-components';
import Button from '../../components/common/button/Button';
import DatePickerComponent from '../common/Date/DatePickerComponent';

import { FormWrapper, InputLabel, TextInput, SelectInput, BtnWrapper, InputGroup, DatePickerWrapper, AlertText } from '../../styles/Components';

const RetentionSearchBar = ({ resultData, setResultData, handleSearch, fetchData, setRetention, setExcelBtn }) => {
	// 초기 날짜 세팅
	let d = new Date();
	const START_DATE = new Date(new Date(d.setDate(d.getDate() - 1)).setHours(0, 0, 0, 0));
	const END_DATE = new Date(new Date(d.setDate(d.getDate() - 1)).setHours(24, 0, 0, 0));
	const [errorMessage, setErrorMessage] = useState('');
	const [period, setPeriod] = useState(0);

	// resultData에 임의 날짜 넣어주기
	useEffect(() => {
		setResultData({
			send_dt: START_DATE,
			end_dt: '',
			retention: 0,
		});
	}, []);

	// 발송 날짜 세팅 로직
	const handleSelectedDate = data => {
		const sendDate = new Date(data);
		const resultSendData = new Date(sendDate.getFullYear(), sendDate.getMonth(), sendDate.getDate());

		const resultEndDate = new Date(resultSendData);
		resultEndDate.setDate(resultEndDate.getDate() + Number(resultData.retention));

		setResultData({ ...resultData, send_dt: resultSendData, end_dt: resultEndDate });
	};

	// // 발송 날짜 세팅 로직
	// const handleEndDate = data => {
	// 	const endDate = new Date(data);
	// 	const resultSendData = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());

	// 	setResultData({ ...resultData, end_dt: resultSendData });
	// };

	// Retention 세팅 로직
	const handleRetention = e => {
		const value = e.target.value;

		const resultEndDate = new Date(resultData.send_dt);
		resultEndDate.setDate(resultEndDate.getDate() + Number(value));

		setResultData({ ...resultData, end_dt: resultEndDate, retention: value });
		setPeriod(value);
	};

	//Retention 범위 선택 후 disable 처리 로직
	const handleSearchBtn = e => {
		e.preventDefault();

		if(period == 0) {
			setErrorMessage("필수값을 선택하세요.");
			return false;
		} else {
			setErrorMessage("");
			setExcelBtn(false); //활성화
			handleSearch(resultData.send_dt, resultData.end_dt);
		} 
	}

	const handleReset = e => {
		e.preventDefault();
		setResultData({ send_dt: START_DATE, end_dt: '', retention: 0 });
		setRetention(1);
		setErrorMessage("");
		setPeriod(1);
		setExcelBtn(true); //비활성화 

		fetchData(START_DATE, END_DATE);
	};

	return (
		<>
			<FormWrapper>
				<SearchbarStyle>
					<SearchItem>
						<InputLabel>집계 기준일</InputLabel>
						<InputGroup>
							<DatePickerWrapper>
								<DatePickerComponent 
									name="시작 일자" selectedDate={resultData.send_dt} 
									handleSelectedDate={data => handleSelectedDate(data)} 
									maxDate={new Date()} />
								<span>~</span>
								<DatePickerComponent 
									name="종료 일자" 
									selectedDate={resultData.end_dt} 
									maxDate={new Date()} 
									readOnly={true} 
									disabled={true} 
									type="retention" />
							</DatePickerWrapper>
						</InputGroup>
					</SearchItem>
					<SearchItem>
						<InputLabel>Retention 범위</InputLabel>
						<SelectInput 
							onChange={e => handleRetention(e)} value={resultData.retention}>
							<option value={0}>선택</option>
							<option value={1}>D+1</option>
							<option value={7}>D+7</option>
							<option value={30}>D+30</option>
						</SelectInput>
					</SearchItem>
					{/* 기획 보류 */}
					{/* <SearchItem>
						<InputLabel>조회 국가</InputLabel>
						<SelectInput>
							<option value="">ALL</option>
							<option value="">KR</option>
							<option value="">EN</option>
							<option value="">JP</option>
							<option value="">TH</option>
						</SelectInput>
					</SearchItem> */}
					<BtnWrapper $gap="8px">
						<Button theme="reset" handleClick={handleReset} />
						<Button
							theme="search"
							text="검색"
							handleClick={handleSearchBtn}
						/>
						<AlertText>{errorMessage}</AlertText>
					</BtnWrapper>
				</SearchbarStyle>
			</FormWrapper>
		</>
	);
};

export default RetentionSearchBar;

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;
	}
`;
