import styled, { css } from 'styled-components';
import { useForm } from 'react-hook-form';
import { useState, useEffect, Fragment } from 'react';
import Button from '../common/button/Button';

import Modal from '../common/modal/Modal';
import { Title, BtnWrapper, InputGroup, TableStyle, AlertText } from '../../styles/Components';

import { BlackListExcelDown, BlackListMultipleUpload } from '../../apis';

const UserBlockUploadBtn = ({ disabled, setGuidList, guidList, typeError, setTypeError }) => {
	const token = sessionStorage.getItem('token');

	// onchange states
	const [file, setFile] = useState(null);
	const [previewModal, setPreviewModal] = useState('hidden');

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

		if (previewModal === 'hidden') {
			setPreviewModal('view');
		} else if (previewModal === 'view') {
			setPreviewModal('hidden');
		}
	};

	// onchange event
	const handleFile = async e => {
		let fileTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'];

		setFile(e.target.files[0]);
		setGuidList(await BlackListMultipleUpload(token, e.target.files[0]));
	};

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

		document.querySelector('#fileinput').value = '';
		setGuidList([]);
		setTypeError(true);
		setFile(null);
	};

	useEffect(() => {
		if (typeof guidList === 'undefined') {
			setTypeError(true);
		} else if (typeof guidList !== 'undefined') {
			if (guidList.length > 0) {
				setTypeError(false);
			}
		}
	});

	const handleDownloadExcel = async () => {
		const token = sessionStorage.getItem('token');
		await BlackListExcelDown(token, 'block_sample.xlsx');
	};

	return (
		<>
			{/* form */}
			<div className="form-group custom-form">
				<FileWrapper>
					<Label>제재 대상(복수)</Label>
					<InputGroup>
						<FileInput type="file" width="300px" required onChange={handleFile} id="fileinput" disabled={disabled} />
						{file ? <FileButton onClick={handleFileDelete}>파일 삭제</FileButton> : <FileButton htmlFor="fileinput" disabled={disabled}>엑셀 업로드</FileButton>}
						{typeError === false ? (
							<Button text="미리보기" theme="line" handleClick={e => handlePreview(e)} />
						) : (
							typeof guidList === 'undefined' && <AlertText>유효하지 않은 파일입니다.</AlertText>
						)}
						<FileButton onClick={handleDownloadExcel} disabled={disabled}>샘플 다운로드</FileButton>
					</InputGroup>
				</FileWrapper>
			</div>
			<Modal $bgcolor="transparent" min="300px" $view={previewModal}>
				<Title $align="center">업로드 미리보기</Title>
				<Count>총 제재 인원 : 45</Count>
				<TableWrapper>
					<TableStyle>
						<thead>
							<tr>
								<th width="300">GUID</th>
								<th width="200">닉네임</th>
								<th width="120">유효성 체크</th>
							</tr>
						</thead>
						<tbody>
							{guidList &&
								guidList.map((data, idx) => (
									<Fragment key={idx}>
										<tr>
											<td>{data.guid}</td>
											<td>{data.nickname}</td>
											{data.validate === true ? <State color="#007A00">true</State> : <State color="#d60000">false</State>}
										</tr>
									</Fragment>
								))}
						</tbody>
					</TableStyle>
				</TableWrapper>
				<BtnWrapper $justify="center">
					<Button theme="line" text="확인" handleClick={e => handlePreview(e)} />
				</BtnWrapper>
			</Modal>
		</>
	);
};

export default UserBlockUploadBtn;

const Label = styled.div`
	display: block;
	min-width: 120px;
	text-align: center;
`;

const FileWrapper = styled.div`
	display: inline-flex;
	align-items: center;

	margin-right: 20px;
	button {
		height: 35px;
	}
`;

const FileButton = styled.label`
	border-radius: 5px;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	min-width: fit-content;
	font-size: 14px;
	background: #2c2c2c;
	color: #fff;
	width: 100px;
	height: 35px;
	cursor: pointer;

    ${props =>
		props.disabled &&
		css`
		background: #b8b8b8;
		cursor: not-allowed;
	`}
`;

const FileInput = styled.input`
	height: 35px;
	border: 1px solid #e0e0e0;
	border-radius: 5px;
	width: 300px;
	padding: 0 15px;
	line-height: 35px;
	font-size: 14px;
	cursor: pointer;
	&::file-selector-button {
		display: none;
	}
	&:disabled {
		color: #cccccc;
		background: #f6f6f6;
	}
`;

const TableWrapper = styled.div`
	margin-top: 5px;
	margin-bottom: 30px;
	max-height: 324px;
	overflow: auto;
	&::-webkit-scrollbar {
		width: 4px;
	}
	&::-webkit-scrollbar-thumb {
		background: #666666;
	}
	&::-webkit-scrollbar-track {
		background: #d9d9d9;
	}
`;

const Count = styled.div`
	font-size: 14px;
`;

const State = styled.td`
	color: ${props => props.color};
`;
