import { useState, useEffect } from 'react';
import DatePickerComponent from '../common/Date/DatePickerComponent';
import styled from 'styled-components';
import TitleArrow from '../../assets/img/icon/icon-title.png';
import Button from '../../components/common/button/Button';

import { SelectInput, InputLabel, DatePickerWrapper, FormWrapper } from '../../styles/Components';
import { ReportTotalView } from '../../apis/Report';
import { HourList, MinuteList } from '../../assets/data';

const ReportListSummary = () => {
	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();

	const token = sessionStorage.getItem('token');

	const [summaryState, setSummaryState] = useState('active');
	const [dataList, setDataList] = useState({});

	const [sendHour, setSendHour] = useState('00');
	const [sendMin, setSendMin] = useState('00');

	const [endHour, setEndHour] = useState('00');
	const [endMin, setEndMin] = useState('00');

	const [resultData, setResultData] = useState({
		send_dt: START_DATE,
		end_dt: END_DATE,
	});

	useEffect(() => {
		fetchData(START_DATE, END_DATE);
	}, []);

	const fetchData = async (startDate, endDate) => {
		setDataList(await ReportTotalView(token, startDate && new Date(startDate).toISOString().split('.')[0], endDate && new Date(endDate).toISOString().split('.')[0]));
	};

	const handleSummary = () => {
		if (summaryState === 'active') {
			setSummaryState('inactive');
		} else {
			setSummaryState('active');
		}
	};

	// 발송 시간 세팅 로직
	const handleSendTime = e => {
		let sendDate = '';

		if (resultData.send_dt.length === 0 || typeof resultData.send_dt.length != 'undefined') {
			sendDate = new Date();
		} else {
			sendDate = new Date(resultData.send_dt);
		}

		if (e.target.id === 'hour') setSendHour(e.target.value);
		else if (e.target.id === 'min') setSendMin(e.target.value);

		const result = new Date(sendDate.getFullYear(), sendDate.getMonth(), sendDate.getDate(), e.target.id === 'hour' ? e.target.value : sendHour, e.target.id === 'min' ? e.target.value : sendMin);

		setResultData({ ...resultData, send_dt: result });
	};

	// 발송 날짜 세팅 로직
	const handleSelectedDate = data => {
		const sendDate = new Date(data);

		const resultSendData = new Date(sendDate.getFullYear(), sendDate.getMonth(), sendDate.getDate(), sendHour, sendMin);

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

	const handleEndTime = e => {
		let endDate = '';

		if (resultData.end_dt.length === 0 || typeof resultData.end_dt.length != 'undefined') {
			endDate = new Date();
		} else {
			endDate = new Date(resultData.end_dt);
		}

		if (e.target.id === 'hour') setEndHour(e.target.value);
		else if (e.target.id === 'min') setEndMin(e.target.value);

		const result = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(), e.target.id === 'hour' ? e.target.value : endHour, e.target.id === 'min' ? e.target.value : endMin);

		setResultData({ ...resultData, end_dt: result });
	};

	// 발송 날짜 세팅 로직
	const handleEndDate = data => {
		const endDate = new Date(data);

		const resultSendData = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(), endHour, endMin);

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

	return (
		<ReportSummaryContainer>
			<SummaryTitle onClick={handleSummary} $state={summaryState}>
				Summary
			</SummaryTitle>
			<SummaryInfo $state={summaryState}>
				<ReportBarWrapper>
					<StateBar $percent={dataList && dataList.rate} />
				</ReportBarWrapper>
				<ReportInfo>
					<ReportItem>
						<InfoTitle>총 신고건수</InfoTitle>
						<InfoCount>{dataList && dataList.totalCnt}</InfoCount>
					</ReportItem>
					<ReportItem>
						<InfoTitle>해결</InfoTitle>
						<InfoCount>{dataList && dataList.resolve}</InfoCount>
					</ReportItem>
					<ReportItem>
						<InfoTitle>미해결</InfoTitle>
						<InfoCount $color={dataList && dataList.unresolve > 0 && '#d60000'}>{dataList && dataList.unresolve}</InfoCount>
					</ReportItem>
					<ReportItem>
						<InfoTitle>완료율</InfoTitle>
						<InfoCount>{dataList && dataList.rate}</InfoCount>
					</ReportItem>
				</ReportInfo>

				<FormWrapper>
					<ReportSetting>
						<InputLabel>
							집계 기간<span>(* 10분 단위 집계)</span>
						</InputLabel>
						<DatePickerWrapper>
							<InputGroup>
								<DatePickerWrapper>
									<DatePickerComponent 
										name="시작 일자" 
										selectedDate={resultData.send_dt} 
										handleSelectedDate={data => handleSelectedDate(data)} />
								</DatePickerWrapper>
								<SelectInput onChange={e => handleSendTime(e)} id="hour">
									{HourList.map(hour => (
										<option value={hour} key={hour}>
											{hour}
										</option>
									))}
								</SelectInput>
								<SelectInput onChange={e => handleSendTime(e)} id="min">
									{MinuteList.map(min => (
										<option value={min} key={min}>
											{min}
										</option>
									))}
								</SelectInput>
							</InputGroup>
							<span>~</span>
							<InputGroup>
								<DatePickerWrapper>
									<DatePickerComponent 
									name="종료 일자" 
									selectedDate={resultData.end_dt} 
									handleSelectedDate={data => handleEndDate(data)}
									pastDate = {resultData.send_dt} 
									maxDate={new Date()} />
								</DatePickerWrapper>
								<SelectInput onChange={e => handleEndTime(e)} id="hour">
									{HourList.map(hour => (
										<option value={hour} key={hour}>
											{hour}
										</option>
									))}
								</SelectInput>
								<SelectInput onChange={e => handleEndTime(e)} id="min">
									{MinuteList.map(min => (
										<option value={min} key={min}>
											{min}
										</option>
									))}
								</SelectInput>
							</InputGroup>
						</DatePickerWrapper>
						<Button
							theme="search"
							text="집계"
							handleClick={e => {
								e.preventDefault();
								fetchData(resultData.send_dt, resultData.end_dt);
							}}
						/>
					</ReportSetting>
				</FormWrapper>
			</SummaryInfo>
		</ReportSummaryContainer>
	);
};

export default ReportListSummary;

const InputGroup = styled.div`
	display: flex;
	${SelectInput} {
		margin-left: 5px;
	}
`;

const ReportSummaryContainer = styled.div`
	background: #f6f6f6;
	border-radius: 10px;
	margin-bottom: 20px;
`;

const SummaryTitle = styled.div`
	font-size: 24px;
	font-weight: 600;
	line-height: 52px;
	padding: 0 10px;
	cursor: pointer;
	&:after {
		content: '';
		display: inline-block;
		width: 11px;
		height: 52px;
		margin-left: 10px;
		background: url(${TitleArrow}) 50% 50% no-repeat;
		position: absolute;
		transform: ${props => (props.$state === 'active' ? 'rotate(0)' : 'rotate(180deg)')};
	}
`;
const SummaryInfo = styled.div`
	display: ${props => (props.$state === 'active' ? 'flex' : 'none')};
	border-top: 1px solid #d9d9d9;
	flex-flow: column;
	gap: 25px;
	padding: 30px 20px;

	${SelectInput} {
		height: 35px;
	}
	${DatePickerWrapper} {
		justify-content: center;
	}
`;
const ReportBarWrapper = styled.div`
	width: 90%;
	display: block;
	margin: auto;
	height: 10px;
	overflow: hidden;
	background: #cccccc;
	border-radius: 10px;
`;

const StateBar = styled.div`
	height: 10px;
	width: ${props => props.$percent};
	background: #666;
	border-radius: 10px;
`;

const ReportInfo = styled.div`
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	align-items: center;
	gap: 10px 40px;
`;
const ReportItem = styled.div`
	display: flex;
	gap: 20px;
	font-size: 20px;
`;

const InfoTitle = styled.div``;

const InfoCount = styled.div`
	font-weight: 600;
	color: ${props => props.$color};
`;

const ReportSetting = styled.div`
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	align-items: center;
	gap: 20px;
	${InputLabel} {
		span {
			font-size: 12px;
			font-weight: 400;
		}
	}
`;
