import { useState, useEffect } from 'react';
import { styled } from 'styled-components';
import { Title, BtnWrapper, TextInput, Label, Textarea, InputItem, ModalText, SearchBarAlert } from '../../../styles/Components';

import { RepostReplyMessage } from '../../../apis/Report';

import Modal from '../../common/modal/Modal';
import Button from '../../common/button/Button';
import CloseIcon from '../../../assets/img/icon/icon-close.png';

const ReportListAnswerModal = ({ answerView, setAnswerView, detailData, replyData, pkId, skId }) => {
	const token = sessionStorage.getItem('token');
	const [replied, setReplied] = useState(false);

	// 버튼 validation -> true 일 때 disable 처리
	const [isNullValue, setIsNullValue] = useState(false);

	// 발송 API 전달용 resultData 세팅
	const [resultData, setResultData] = useState({
		pk: '',
		sk: '',
		title: '',
		detail: '',
		reporter_nickname: '',
	});

	// 모달 , 모달 메세지용 state
	const [modalStep, setModalStep] = useState(false);
	const [modalText, setModalText] = useState('');
	const [confirmModal, setConfirmModal] = useState('hidden');
	const [completeModal, setCompleteModal] = useState('hidden');

	// 답변 조회 DATA 세팅용 resultData
	useEffect(() => {
		// 답변 조회 api에 호출할 pk, sk 세팅용
		const pk = encodeURI(pkId);
		const sk = encodeURI(skId);

		setResultData({
			pk: pkId && pk,
			sk: skId && sk,
			title: replyData ? replyData.title : '',
			detail: replyData ? replyData.detail : '',
			reporter_nickname: detailData && detailData.reporter_nickname,
		});

		// 답변 유무 확인용
		replyData ? setReplied(true) : setReplied(false);
	}, [detailData, replyData]);
	// console.log('신고답변작성 : ', resultData);

	// Button Validation용 if 문
	const btnVali = resultData.title && resultData.title.length > 0 && resultData.detail && resultData.detail.length > 0;

	const titleLeng = resultData.title && resultData.title.length;
	const detailLeng = resultData.detail && resultData.detail.length;

	// Button Validation (2) - 에러 메세지
	const handleNullVali = e => {
		if (btnVali) {
			setIsNullValue(false);
		} else {
			setIsNullValue(true);
		}
	};

	// 텍스트 변경 함수
	const handleNoticeText = e => {
		let btnName = e.target.name;

		if (btnName === '취소버튼') {
			setModalText('신고 답변을 취소하시겠습니까? \n 취소 시 작성된 모든 정보가 사라집니다.');
			setModalStep(false);
		} else {
			setModalText('신고 답변 우편을 발송하시겠습니까?');
			setModalStep(true);
		}
	};

	// 확인 모달
	const handleConfirmModal = e => {
		if (confirmModal === 'hidden') {
			setConfirmModal('view');
		} else {
			setConfirmModal('hidden');
		}
	};

	// 완료 모달창
	const handleCompleteModal = () => {
		if (completeModal === 'hidden') {
			setCompleteModal('view');
		} else {
			setCompleteModal('hidden');
			window.location.reload();
		}
	};

	// 확인 모달창에서 취소, 확인 버튼 처리
	const handleModalStep = async e => {
		e.preventDefault();
		handleConfirmModal();

		if (modalStep) {
			await RepostReplyMessage(token, resultData);
			setModalText('답변 발송이 완료되었습니다.');
			handleCompleteModal();
		} else {
			setModalText('답변이 취소되었습니다.');
			handleCompleteModal();
		}

		handleReset();
	};

	// 확인 버튼에서 불러올 초기화 처리
	const handleReset = () => {
		setAnswerView('hidden');
	};

	return (
		<>
			<Modal min="960px" $view={answerView}>
				<Title $align="center">{replied ? '신고 답변' : '신고 답변 작성'}</Title>
				<Subtitle>[답변 수신자 정보]</Subtitle>
				<ReportDetailState>
					<table>
						<caption></caption>
						<tbody>
							<tr>
								<th width="100px">수신자 GUID</th>
								<td>
									<TextInput value={detailData.reporter_guid || ''} readOnly />
								</td>
								<th width="100px">닉네임</th>
								<td>
									<TextInput value={detailData.reporter_nickname || ''} readOnly />
								</td>
							</tr>
							<tr>
								<th>제목</th>
								<td colSpan="3">{detailData.title || ''}</td>
							</tr>
							<tr>
								<th width="120">발송 경로</th>
								<td>개인 우편함</td>
								<th width="120">발송자</th>
								<td>GM</td>
							</tr>
						</tbody>
					</table>
				</ReportDetailState>

				<Subtitle>[답변 내용]</Subtitle>
				<AnswerRegistTable>
					<tbody>
						<tr>
							<th width="120">
								<Label>제목</Label>
							</th>
							<td>
								<InputItem>
									<TextInput
										maxLength="30"
										name="title"
										value={resultData.title || ''}
										onInput={e => {
											setResultData({ ...resultData, title: e.target.value.trimStart() });
										}}
										readOnly={replyData}
									/>
								</InputItem>
								{/* 답변 작성시에 글자 수 확인 */}
								<ReportNotice $color={titleLeng > 29 ? 'red' : '#666'}>* 최대 등록 가능 글자수 ({Number(titleLeng)}/30자)</ReportNotice>
							</td>
						</tr>
						<tr>
							<th>
								<Label>내용</Label>
							</th>
							<td>
								<Textarea
									value={resultData.detail || ''}
									name="detail"
									maxLength="2000"
									onInput={e => {
										setResultData({ ...resultData, detail: e.target.value.trimStart() });
									}}
									readOnly={replyData}
								/>
								{/* 답변 작성시에 글자 수 확인 */}
								<ReportNotice $color={detailLeng > 1999 ? 'red' : '#666'}>* 최대 등록 가능 글자수 ({Number(detailLeng)}/2000자)</ReportNotice>
							</td>
						</tr>
					</tbody>
				</AnswerRegistTable>
				{isNullValue && (
					<SearchBarAlert $align="right" $padding="15px">
						필수값을 입력해주세요.
					</SearchBarAlert>
				)}
				<BtnWrapper $justify="flex-end" $gap="10px">
					{replyData ? (
						<Button text="확인" theme="line" handleClick={e => setAnswerView('hidden')} />
					) : (
						<>
							<Button
								text="취소"
								theme="line"
								name="취소버튼"
								handleClick={e => {
									handleConfirmModal(e);
									handleNoticeText(e);
								}}
							/>
							<Button
								text="발송"
								name="발송버튼"
								// errorMessage={btnValidation}
								theme={btnVali ? 'primary' : 'disable'}
								handleClick={e => {
									{
										!btnVali ? handleNullVali(e) : handleConfirmModal(e);
										handleNoticeText(e);
										handleNullVali(e);
									}
								}}
							/>
						</>
					)}
				</BtnWrapper>
			</Modal>

			{/* 확인 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmModal}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleConfirmModal} />
				</BtnWrapper>
				<ModalText $align="center">{modalText}</ModalText>
				<BtnWrapper $gap="10px">
					<Button text="취소" theme="line" size="large" width="100%" handleClick={handleConfirmModal} />
					<Button
						text="확인"
						theme="primary"
						type="submit"
						size="large"
						width="100%"
						handleClick={e => {
							handleModalStep(e);
						}}
					/>
				</BtnWrapper>
			</Modal>
			{/* 완료 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={completeModal}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleCompleteModal} />
				</BtnWrapper>
				<ModalText $align="center">{modalText}</ModalText>
				<BtnWrapper $gap="10px">
					<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleCompleteModal} />
				</BtnWrapper>
			</Modal>
		</>
	);
};

export default ReportListAnswerModal;

const ReportDetailState = styled.div`
	border-top: 1px solid #000;
	border-bottom: 1px solid #000;
	padding: 15px 10px;
	font-size: 14px;
	margin-bottom: 20px;
	input {
		height: 35px;
		max-width: 330px;
		font-size: 14px;
		padding: 5px 10px;
	}
	table {
		tr {
			th,
			td {
				padding: 5px;
				height: 45px;
				vertical-align: middle;
			}
		}
	}
`;

const Subtitle = styled.div`
	font-size: 16px;
	font-weight: 500;
	line-height: 1.6;
`;

const AnswerRegistTable = styled.table`
	border-top: 1px solid #999;
	margin-bottom: 20px;
	th,
	td {
		padding: 15px 0;
		border-bottom: 1px solid #f6f6f6;
	}
	tr:last-child {
		th,
		td {
			padding: 15px 0;
			border-bottom: 1px solid #999;
		}
	}
	th {
		vertical-align: top;
		line-height: 30px;
	}
	td {
		${TextInput} {
			max-width: 600px;
		}
		${Textarea} {
			width: 100%;
			border: 1px solid #d9d9d9;
			border-radius: 5px;
			height: 150px;
			padding: 15px;
			&:focus {
				border: 1px solid #2c2c2c;
			}
		}
	}
`;

const ReportNotice = styled.span`
	font-size: 12px;
	font-weight: 300;
	color: ${props => props.$color || '#999'};
	margin-top: 10px;
	display: block;
`;

const ButtonClose = styled.button`
	width: 16px;
	height: 16px;
	background: url(${CloseIcon}) 50% 50% no-repeat;
	opacity: ${props => props.opacity};
`;
