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

import Modal from '../common/modal/Modal';
import { BtnWrapper, ButtonClose, ModalText, InputLabel, InputGroup, AlertText } from '../../styles/Components';
import { WhiteListMultiRegsit, WhiteListExelUpload } from '../../apis';

const WhiteListUploadBtn = () => {
	const token = sessionStorage.getItem('token');
	const [doubleSubmitFlag, setDoubleSubmitFlag] = useState(false);

	// onchange states
	const [excelFile, setExcelFile] = useState(null);

	const [registModalClose, setRegistModalClose] = useState('hidden');
	const [completeModalClose, setCompleteModalClose] = useState('hidden');
	const [fileResponse, setFileResponse] = useState('');

	const [alertMessage, setAlertMessage] = useState("");
	const [updateMessage, setUpdateMessage] = useState('등록이 완료되었습니다.');

	// 등록 확인 모달
	const handleRegistModalClose = (e) => {
		e.preventDefault();

		if (registModalClose === 'hidden') {
			setRegistModalClose('view');
		} else {
			setRegistModalClose('hidden');
		}
	};

	// 등록 완료 모달
	const handleCompleteModalClose = () => {
		if (completeModalClose === 'hidden') {
			setCompleteModalClose('view');
		} else {
			setCompleteModalClose('hidden');
			window.location.reload();
		}
	};

	// onchange event
	const handleFile = async e => {
		setExcelFile(e.target.files[0]);

		const message = await WhiteListExelUpload(token, e.target.files[0]);
		const uploadMessage = message.data.data.message;

		if (uploadMessage === '파일 업로드 하였습니다.') {
			setAlertMessage('')
		} else if (fileResponse === 'Maximum upload size exceeded' || fileResponse === 'guid를 확인해주세요.' || uploadMessage === 'Excel 파일을 선택해주세요.') {
			setAlertMessage('유효하지 않은 파일입니다.')
		} else {
			setAlertMessage('중복된 유저 정보가 있습니다.');
		}

		setFileResponse(message.data.data.message);
	};

	// 저장된 엑셀 파일 -> API 로 전송
	const handlePostGuid = async e => {
		e.preventDefault();

		if (fileResponse === '파일 업로드 하였습니다.') {
			await WhiteListMultiRegsit(token, excelFile);
			setUpdateMessage('등록이 완료되었습니다.');
		} else if (fileResponse === 'Maximum upload size exceeded' || fileResponse === 'guid를 확인해주세요.' ) {
			setUpdateMessage('유효하지 않은 파일입니다');
		} else {
			setUpdateMessage('파일 내 중복된 유저 정보가 있습니다. \n 파일을 다시 확인 후 이용해주세요.');
		}

		setRegistModalClose('hidden');
		handleCompleteModalClose();
	};

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

		document.querySelector('#fileinput').value = '';
		setAlertMessage('');

		setExcelFile(null);
	};

	return (
		<>
			{/* form */}
			<div className="form-group custom-form">
				<FileWrapper>
					<InputLabel>일괄등록</InputLabel>
					<InputGroup>
						<FileInput type="file" width="300px" required onChange={handleFile} id="fileinput" />
						{excelFile ? 
							<FileButton onClick={handleFileDelete}>파일 삭제</FileButton> 
							: <FileButton htmlFor="fileinput">엑셀 업로드</FileButton>}
						{excelFile && 
						<Button 
							theme={alertMessage.length > 0 ? 'gray' : 'search'} 
							text="등록" 
							errorMessage={alertMessage.length > 0}
							handleClick={e => {
								handleRegistModalClose(e);
							}}
						/>}
						<AlertText>{alertMessage}</AlertText>
					</InputGroup>
				</FileWrapper>
			</div>

			{/* 일괄등록 모달창 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={registModalClose}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleRegistModalClose} />
				</BtnWrapper>
				<ModalText $align="center">
					화이트리스트 명단에
					<br />
					일괄 등록하시겠습니까?
				</ModalText>
				<BtnWrapper $gap="10px">
					<Button 
						text="취소" 
						theme="line" 
						size="large" 
						width="100%" 
						handleClick={handleRegistModalClose} 
					/>
					<Button
						text="확인"
						theme="primary"
						type="submit"
						size="large"
						width="100%"
						handleClick={e => {
							e.preventDefault();
							doubleSubmitFlag || handlePostGuid(e);
							setDoubleSubmitFlag(true);
						}}
					/>
				</BtnWrapper>
			</Modal>

			{/* 등록 완료 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={completeModalClose}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleCompleteModalClose} />
				</BtnWrapper>
				<ModalText $align="center">{updateMessage}</ModalText>
				<BtnWrapper $gap="10px">
					<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleCompleteModalClose} />
				</BtnWrapper>
			</Modal>
		</>
	);
};

export default WhiteListUploadBtn;

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

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

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