'use client';

import './style.scss';
import Link from 'next/link';
import { useState, useEffect } from 'react';
import { useMemberContext } from '@/contexts/memberProvider';
import { ChangeApproveRequest } from '@/types/request/account';
import { fetchApi } from '@/lib/utils/client';
import Loading from '@/app/component/Loading';

export default function ChangeApprove()
{
	const { member, setMember } = useMemberContext();
	const [error, setError] = useState<string>('');
	const [loading, setLoading] = useState<boolean>(false);
	const [notifications, setNotifications] = useState({
		isReceiveSMS: member?.memberApprove.isReceiveSMS || false,
		isReceiveEmail: member?.memberApprove.isReceiveEmail || false,
		isReceiveNote: member?.memberApprove.isReceiveNote || false
	});

	useEffect(() => {
		if (error) {
			alert(error);
			setError('');
		}
	}, [error]);

	useEffect(() => {
		if (member) {

			const approve = member.memberApprove;
			setNotifications({
				isReceiveSMS: approve?.isReceiveSMS ?? false,
				isReceiveEmail: approve?.isReceiveEmail ?? false,
				isReceiveNote: approve?.isReceiveNote ?? false
			});
		}
	}, [member]);

	const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
		e.preventDefault();

		if (!member) {
			return;
		}

		setLoading(true);

		fetchApi('/api/mypage/receive-settings', {
			method: 'POST',
			body: {
				IsReceiveSMS: notifications.isReceiveSMS,
				IsReceiveEmail: notifications.isReceiveEmail,
				IsReceiveNote: notifications.isReceiveNote
			} as ChangeApproveRequest
		}).then(() => {
			member.memberApprove.isReceiveSMS = notifications.isReceiveSMS;
			member.memberApprove.isReceiveEmail = notifications.isReceiveEmail;
			member.memberApprove.isReceiveNote = notifications.isReceiveNote;
			setMember(member);
			localStorage.setItem('member', JSON.stringify(member));
			alert("수신 설정이 변경되었습니다.");

		}).catch(err => {
			setError(err.message);
		}).finally(() => {
			setLoading(false);
		});
	}

	const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const { name, checked } = e.target;

		setNotifications((prev) => ({
			...prev,
			[name]: checked
		}));
	};

	return (
		<div id="changeApprove">
			{ loading && <Loading /> }

			<h1>알림 수신 설정</h1>
			<form method="post" acceptCharset="utf-8" autoComplete="off" onSubmit={handleSubmit}>
				<table className="table-auto max-xl:w-full lg:w-[600px]">
					<caption>
						보다 편리한 서비스 이용을 위해 원하는 알림 수신 여부를 설정할 수 있습니다.
					</caption>
					<colgroup>
						<col width="30%"/>
						<col width="60%"/>
					</colgroup>
					<tbody>
						<tr>
							<th>SMS 수신</th>
							<td>
								<label>
									<input
										type="checkbox"
										name="isReceiveSMS"
										checked={notifications.isReceiveSMS}
										onChange={handleChange}
									/>
									수신합니다.
								</label>
							</td>
						</tr>
						<tr>
							<th>이메일 수신</th>
							<td>
								<label>
									<input
										type="checkbox"
										name="isReceiveEmail"
										checked={notifications.isReceiveEmail}
										onChange={handleChange}
									/>
									수신합니다.
								</label>
							</td>
						</tr>
						<tr>
							<th>쪽지 수신</th>
							<td>
								<label>
									<input
										type="checkbox"
										name="isReceiveNote"
										checked={notifications.isReceiveNote}
										onChange={handleChange}
									/>
									수신합니다.
								</label>
							</td>
						</tr>
					</tbody>
					<tfoot>
						<tr>
							<td colSpan={2}>
								<div className="flex justify-center gap-2">
									<button type="submit" className="btn btn-submit">확인</button>
									<Link href="/profile" className="btn btn-default">취소</Link>
								</div>
							</td>
						</tr>
					</tfoot>
				</table>
			</form>

			<br />
			<dl className="max-xl:w-full lg:w-[600px]">
				<dt hidden>&nbsp;</dt>
				<dd>
					<ol>
						<li>수신을 거부하더라도 계정 보안 및 필수 서비스 공지는 계속 받을 수 있습니다.</li>
						<li>프로모션 및 이벤트 소식을 받고 싶다면 수신을 활성화하세요.</li>
					</ol>
				</dd>
			</dl>
		</div>
	);
}