import PrimaryButton from "@/components/button/PrimaryButton";
import SecondaryButton from "@/components/button/SecondaryButton";
import PasswordInput from "@/components/input/PasswordInput";
import RaidBuilderModal from "@/components/modal/RaidBuilderModal";
import { useResetPassword } from "@/hooks/AccountHooks";
import { Account } from "@/interface/Account";
import { useTimedModal } from "@/providers/TimedModalProvider";
import { useEffect, useState } from "react";


export default function AccountPasswordRestModal({
	display,
	close,
	account
}:{
	display: boolean;
	close: () => void;
	account: Account | undefined;
}){
	const [ newPassword, setNewPassword ] = useState<string>("");
	const { addSuccessMessage, addErrorMessage } = useTimedModal();


	const passwordResetMutate = useResetPassword(account?.accountId ?? "");
	const modalId = crypto.randomUUID().replace("-", "");


	const resetPassword = () => {
		passwordResetMutate.mutate(newPassword);
	}

	useEffect(() => {
		if(passwordResetMutate.isSuccess){
			passwordResetMutate.reset();
			addSuccessMessage(`Successfully reset password for ${account?.username}`);
			close();
		}
		else if(passwordResetMutate.isError){
			passwordResetMutate.reset();
			addErrorMessage(`Failed to reset password for ${account?.username}: ${passwordResetMutate.error.message}`);
			console.log(passwordResetMutate.error);
		}
	});


	return (
		<RaidBuilderModal
			display={display}
			close={close}
			modalHeader={"Reset Password"}
			modalBody={
				<div
					className="flex flex-col gap-4"
				>
					<div>Enter new password for {account?.username}.</div>
					<PasswordInput
						id={`passwordResetModal${modalId}`}
						value={newPassword}
						onChange={(e) => setNewPassword(e.target.value)}
						placeholder="Password"
					/>
				</div>
			}
			modalFooter={
				<>
					<PrimaryButton
						onClick={resetPassword}
					>
						Reset
					</PrimaryButton>
					<SecondaryButton
						onClick={close}
					>
						Cancel
					</SecondaryButton>
				</>
			}
		/>
	);
}
