"use client";

import { useSearchParams } from "next/navigation";

export default function MailVerify() {
    const searchParams = useSearchParams();
    const URLCode = searchParams.get("code");

    let code: string = "";

    if(URLCode){
        code = URLCode;
    }

    const verify = async (e: React.FormEvent<HTMLFormElement>) => {
        if(code === ""){
            code = e.currentTarget.code.value;
        }

        if (code.length !== 6) {
            alert("コードは6桁で入力してください。");
            return;
        }

        const res = await fetch(`${location.origin}/api/mailverify/check`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                code,
            }),
        });
        const data = await res.text();
        const result = JSON.parse(data);

        if (result.status === "success") {
            alert("メール認証に成功しました。\nログインしてください。");
            window.location.href = "/login";
        }
    };

    return (
        <>
        <h1 className="title">メール認証</h1>

        <form onSubmit={verify}>
            <label className="label">コード：</label>
            <input type="text" name="code" defaultValue={code} className="input" placeholder="123456" style={{width: "10rem"}} maxLength={6} />
        </form>
        </>
    )
}