"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import LoginInputSvg from "@/app/svgs/inputformx";
import ResetPasswordDone from "./ResetPasswordDone";
import ResetPaswordOption from "./ResetPaswordOption";
import apiService from "@/app/lib/apiService";

export default function ResetPasswordPage() {
	const [isDoneOpen, setIsDoneOpen] = useState(false);
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [passwordConfirm, setPasswordConfirm] = useState("");
	const [focused, setFocused] = useState<Record<string, boolean>>({});
	const [errors, setErrors] = useState<Record<string, string>>({});

	// 인증번호 관련 상태
	const [emailCodeSent, setEmailCodeSent] = useState(false);
	const [emailCode, setEmailCode] = useState("");
	const [emailCodeVerified, setEmailCodeVerified] = useState(false);

	const isEmailValid = useMemo(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email), [email]);
	const isPasswordValid = useMemo(() => password.length >= 8 && password.length <= 16, [password]);
	const isPasswordConfirmValid = useMemo(() => passwordConfirm === password && passwordConfirm.length > 0, [password, passwordConfirm]);

	const canSubmit = useMemo(() => {
		return isEmailValid && isPasswordValid && isPasswordConfirmValid && emailCodeVerified;
	}, [isEmailValid, isPasswordValid, isPasswordConfirmValid, emailCodeVerified]);

	function validateAll() {
		const nextErrors: Record<string, string> = {};
		if (!isEmailValid) nextErrors.email = "올바른 이메일 형식을 입력해 주세요.";
		if (!isPasswordValid) nextErrors.password = "비밀번호는 8~16자여야 합니다.";
		if (!isPasswordConfirmValid) nextErrors.passwordConfirm = "비밀번호가 일치하지 않습니다.";
		setErrors(nextErrors);
		return Object.keys(nextErrors).length === 0;
	}

	async function handleSendVerificationCode() {
		if (!isEmailValid) return;

		try {
			await apiService.sendPasswordReset(email);
			// 성공 시 상태 업데이트
			setEmailCodeSent(true);
			setEmailCode("");
			setEmailCodeVerified(false);
			// 성공 시 에러 메시지 제거
			setErrors((prev) => {
				const next = { ...prev };
				delete next.email;
				return next;
			});
		} catch (error) {
			const errorMessage = error instanceof Error ? error.message : "네트워크 오류가 발생했습니다.";
			console.error("인증번호 전송 오류:", errorMessage);
			setErrors((prev) => ({ ...prev, email: errorMessage }));
		}
	}

	async function verifyEmailCode() {
		try {
			await apiService.verifyPasswordResetCode(email, emailCode);
			// 인증 성공 시 상태 업데이트
			setEmailCodeVerified(true);
			// 성공 시 에러 메시지 제거
			setErrors((prev) => {
				const next = { ...prev };
				delete next.emailCode;
				return next;
			});
		} catch (error) {
			let errorMessage = error instanceof Error ? error.message : "네트워크 오류가 발생했습니다.";
			// 특정 에러 메시지를 사용자 친화적인 메시지로 변경
			if (errorMessage.includes("잘못되었거나 만료된 코드") || errorMessage.includes("잘못되었거나") || errorMessage.includes("만료된")) {
				errorMessage = "올바르지 않은 인증번호입니다. 인증번호를 확인해주세요.";
			}
			console.error("인증번호 확인 오류:", errorMessage);
			setErrors((prev) => ({ ...prev, emailCode: errorMessage }));
		}
	}

	async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
		e.preventDefault();
		if (!validateAll()) return;

		try {
			await apiService.resetPassword(email, emailCode, password, passwordConfirm);
			// 성공 시 완료 오버레이 표시
			setIsDoneOpen(true);
		} catch (error) {
			const errorMessage = error instanceof Error ? error.message : "네트워크 오류가 발생했습니다.";
			console.error("비밀번호 재설정 오류:", errorMessage);
			setErrors((prev) => ({ ...prev, submit: errorMessage }));
		}
	}

	return (
		<div className="min-h-screen w-full flex flex-col items-center justify-between">
			<ResetPasswordDone
				open={isDoneOpen}
				onClose={() => setIsDoneOpen(false)}
			/>

			<ResetPaswordOption doneModalEnabled={isDoneOpen} setDoneModalEnabled={setIsDoneOpen} />

			<div className="rounded-xl bg-white max-w-[560px] px-[40px] w-full">
				{/* 제목 영역 */}
				<div className="my-15 flex flex-col items-center text-center">
					<div className="text-[24px] font-extrabold leading-[150%] text-neutral-700">
						비밀번호 재설정
					</div>
					<p className="mt-2 text-[18px] font-normal leading-[150%] text-text-label">
						비밀번호 재설정을 위해 아래 정보를 입력해 주세요.
					</p>
				</div>

				<form onSubmit={handleSubmit} className="space-y-6">
					{/* 아이디(이메일) + 인증번호 전송 */}
					<div className="space-y-2">
						<label htmlFor="email" className="text-[15px] font-semibold text-text-label">아이디 (이메일)</label>
						<div className="flex gap-2 items-center">
							<div className="relative flex-1">
								<input
									id="email"
									name="email"
									type="email"
									value={email}
									onChange={(e) => setEmail(e.target.value)}
									onFocus={() => setFocused((p) => ({ ...p, email: true }))}
									onBlur={() => setFocused((p) => ({ ...p, email: false }))}
									placeholder="이메일을 입력해 주세요."
									disabled={emailCodeVerified}
									className={`h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border focus:outline-none text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] disabled:bg-gray-100 disabled:cursor-not-allowed ${emailCodeVerified ? '' : (errors.email ? 'border-error' : 'border-neutral-40 focus:border-neutral-700')}`}
								/>
								{email.trim().length > 0 && focused.email && !emailCodeVerified && (
									<button
										type="button"
										onMouseDown={(e) => { e.preventDefault(); setEmail(""); }}
										aria-label="입력 지우기"
										className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
									>
										<LoginInputSvg />
									</button>
								)}
							</div>
							<button
								type="button"
								disabled={!isEmailValid || emailCodeVerified}
								className={`h-[40px] w-[130px] px-[12px] rounded-[8px] text-[16px] font-semibold ${isEmailValid && !emailCodeVerified ? "bg-[#F1F3F5] text-neutral-700" : "bg-gray-50 text-input-placeholder-text"}`}
								onClick={handleSendVerificationCode}
							>
								{emailCodeSent && !emailCodeVerified ? "인증번호 재전송" : "인증번호 전송"}
							</button>
						</div>
						{errors.email && <p className="text-error text-[13px] leading-tight">{errors.email}</p>}
						{emailCodeSent && (
							<div className="space-y-2" aria-expanded={emailCodeSent}>
								<label htmlFor="emailCode" className="sr-only">인증번호</label>
								<div className="flex gap-2 items-center">
									<div className="relative flex-1">
										<input
											id="emailCode"
											name="emailCode"
											inputMode="numeric"
											value={emailCode}
											onChange={(e) => {
												const onlyDigits = e.target.value.replace(/[^0-9]/g, "");
												setEmailCode(onlyDigits.slice(0, 6));
											}}
											onFocus={() => setFocused((p) => ({ ...p, emailCode: true }))}
											onBlur={() => setFocused((p) => ({ ...p, emailCode: false }))}
											placeholder="인증번호 6자리"
											disabled={emailCodeVerified}
											className="h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border border-neutral-40 focus:outline-none focus:border-neutral-700 text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px] disabled:bg-gray-100 disabled:cursor-not-allowed"
										/>
										{emailCode.trim().length > 0 && focused.emailCode && !emailCodeVerified && (
											<button
												type="button"
												onMouseDown={(e) => { e.preventDefault(); setEmailCode(""); }}
												aria-label="입력 지우기"
												className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
											>
												<LoginInputSvg />
											</button>
										)}
									</div>
									<button
										type="button"
										disabled={emailCodeVerified || emailCode.trim().length === 0}
										className={`h-[40px] w-[130px] px-[12px] rounded-[8px] text-[16px] font-semibold ${!emailCodeVerified && emailCode.trim().length > 0 ? "bg-[#F1F3F5] text-neutral-700" : "bg-gray-50 text-input-placeholder-text"}`}
										onClick={verifyEmailCode}
									>
										{emailCodeVerified ? "인증완료" : "인증하기"}
									</button>
								</div>
								{!errors.emailCode && (
									<p className="text-[13px] leading-[normal] text-primary">
										{emailCodeVerified ? (
											"인증이 완료됐습니다"
										) : (
											<>
												인증 확인을 위해 작성한 이메일로 인증번호를 발송했습니다.
												<br />
												이메일을 확인해 주세요.
											</>
										)}
									</p>
								)}
								{errors.emailCode && <p className="text-error text-[13px] leading-tight">{errors.emailCode}</p>}
							</div>
						)}
					</div>

					{/* 새 비밀번호 */}
					<div className="space-y-2">
						<label htmlFor="password" className="text-[15px] font-semibold text-text-label">새 비밀번호</label>
						<div className="relative">
							<input
								id="password"
								name="password"
								type="password"
								value={password}
								onChange={(e) => setPassword(e.target.value)}
								onFocus={() => setFocused((p) => ({ ...p, password: true }))}
								onBlur={() => setFocused((p) => ({ ...p, password: false }))}
								placeholder="8~16자의 영문/숫자/특수문자를 조합해서 입력해 주세요."
								className="h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border border-neutral-40 focus:outline-none focus:border-neutral-700 text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px]"
							/>
							{password.trim().length > 0 && focused.password && (
								<button
									type="button"
									onMouseDown={(e) => { e.preventDefault(); setPassword(""); }}
									aria-label="입력 지우기"
									className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
								>
									<LoginInputSvg />
								</button>
							)}
						</div>
						{errors.password && <p className="text-error text-[13px] leading-tight">{errors.password}</p>}
					</div>

					{/* 새 비밀번호 확인 */}
					<div className="space-y-2">
						<label htmlFor="passwordConfirm" className="text-[15px] font-semibold text-text-label">새 비밀번호 확인</label>
						<div className="relative">
							<input
								id="passwordConfirm"
								name="passwordConfirm"
								type="password"
								value={passwordConfirm}
								onChange={(e) => setPasswordConfirm(e.target.value)}
								onFocus={() => setFocused((p) => ({ ...p, passwordConfirm: true }))}
								onBlur={() => setFocused((p) => ({ ...p, passwordConfirm: false }))}
								placeholder="비밀번호를 다시 입력해 주세요."
								className="h-[40px] px-[12px] py-[7px] w-full rounded-[8px] border border-neutral-40 focus:outline-none focus:border-neutral-700 text-[18px] text-neutral-700 placeholder:text-input-placeholder-text pr-[40px]"
							/>
							{passwordConfirm.trim().length > 0 && focused.passwordConfirm && (
								<button
									type="button"
									onMouseDown={(e) => { e.preventDefault(); setPasswordConfirm(""); }}
									aria-label="입력 지우기"
									className="absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
								>
									<LoginInputSvg />
								</button>
							)}
						</div>
						{errors.passwordConfirm && <p className="text-error text-[13px] leading-tight">{errors.passwordConfirm}</p>}
					</div>

					{/* 액션 버튼 */}
					<div className="flex gap-3">
						<Link
							href="/login"
							className="h-[40px] flex-1 rounded-[12px] bg-bg-gray-light text-[18px] font-semibold text-center flex items-center justify-center text-basic-text"
						>
							이전
						</Link>
						<button
							type="submit"
							className={`h-[40px] flex-1 rounded-[12px] text-[18px] font-semibold text-center flex items-center justify-center text-white ${canSubmit ? "bg-active-button" : "bg-inactive-button"} cursor-pointer`}
						>
							비밀번호 재설정
						</button>
					</div>
				</form>
			</div>
			<p className="text-center py-[40px] text-[15px] text-basic-text">
				Copyright ⓒ 2025 XL LMS. All rights reserved
			</p>
		</div>
	);
}
