import { Fragment, useEffect, useState } from 'react';

import Button from '../../components/common/button/Button';

import { TableStyle, TableInfo, ListOption, IndexTableWrap } from '../../styles/Components';
import { SegmentSearchBar } from '../../components/IndexManage/index';
import { SegmentIndexExport, SegmentIndexView } from '../../apis';

const SegmentContent = () => {
	const token = sessionStorage.getItem('token');
	const END_DATE = new Date();

	const [dataList, setDataList] = useState([]);
	const [resultData, setResultData] = useState([]);

	const [finishDate, setFinishDate] = useState(END_DATE);

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

	// Retention 지표 데이터
	const fetchData = async endDate => {
		const endDateToLocal =
			endDate.getFullYear() +
			'-' +
			(endDate.getMonth() + 1 < 9 ? '0' + (endDate.getMonth() + 1) : endDate.getMonth() + 1) +
			'-' +
			(endDate.getDate() < 9 ? '0' + endDate.getDate() : endDate.getDate());

		setDataList(await SegmentIndexView(token, endDateToLocal));
		setFinishDate(endDateToLocal);
	};

	// 검색 함수
	const handleSearch = end_dt => {
		fetchData(end_dt);
	};

	// 엑셀 다운로드
	const handleXlsxExport = () => {
		const fileName = 'Caliverse_Segment_Index.xlsx';
		SegmentIndexExport(token, fileName, finishDate);
	};

	return (
		<>
			<SegmentSearchBar setResultData={setResultData} resultData={resultData} handleSearch={handleSearch} fetchData={fetchData} />
			<TableInfo>
				<ListOption>
					<Button theme="line" text="엑셀 다운로드" handleClick={handleXlsxExport} />
				</ListOption>
			</TableInfo>
			<IndexTableWrap>
				<TableStyle>
					<caption></caption>
					<thead>
						<tr>
							<th colSpan="1" width="200">
								{dataList && dataList.start_dt} ~ {dataList && dataList.end_dt}
							</th>
							<th colSpan="2" width="400">
								KIP
							</th>
						</tr>
						<tr>
							{/* <th>국가</th> */}
							<th>세그먼트 분류</th>
							<th>AU</th>
							<th>AU Percentage by User Segment (%)</th>
						</tr>
					</thead>
					<tbody>
						{dataList && dataList.segment &&
							dataList.segment.map((segment, index) => (
								<tr key={index}>
									{/* <td rowSpan="6">TH</td> */}
									<td>{segment.type}</td>
									<td>{segment.au}</td>
									<td>{segment.dif}</td>
								</tr>
							))}
					</tbody>
				</TableStyle>
			</IndexTableWrap>
		</>
	);
};

export default SegmentContent;
