/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import { useRef } from "react";

import {
    Head,
    router,
    useForm,
    usePage,
} from "@inertiajs/react";

import { LoaderCircle } from "lucide-react";

import logo from "../../../images/logo-white.png";

import TextLink from "@/components/text-link";
import InputError from "@/components/input-error";

import { Button } from "@/components/ui/button";

import styles from "./email-verification.module.scss";

export default function EmailVerification() {
    const { flash } =
        usePage<any>().props;

    const inputs = useRef<
        (HTMLInputElement | null)[]
    >([]);

    const {
        data,
        setData,
        post,
        processing,
        errors,
    } = useForm({
        otp: "",
    });

    const otpArray = data.otp
        .padEnd(6, " ")
        .split("")
        .slice(0, 6);

    const handleChange = (
        value: string,
        index: number
    ) => {
        if (!/^\d*$/.test(value)) return;

        const current = data.otp
            .padEnd(6, " ")
            .split("");

        current[index] = value.slice(-1);

        const updated = current
            .join("")
            .replace(/\s/g, "");

        setData("otp", updated);

        if (value && index < 5) {
            inputs.current[index + 1]?.focus();
        }
    };

    const handleKeyDown = (
        e: React.KeyboardEvent<HTMLInputElement>,
        index: number
    ) => {
        if (
            e.key === "Backspace" &&
            !otpArray[index] &&
            index > 0
        ) {
            inputs.current[index - 1]?.focus();
        }
    };

    const handlePaste = (
        e: React.ClipboardEvent<HTMLInputElement>
    ) => {
        e.preventDefault();

        const pasted = e.clipboardData
            .getData("text")
            .replace(/\D/g, "")
            .slice(0, 6);

        setData("otp", pasted);

        const focusIndex =
            pasted.length >= 6
                ? 5
                : pasted.length;

        inputs.current[focusIndex]?.focus();
    };

    const verifyOtp = () => {
        post(
            route("register.verify-otp")
        );
    };

    const resendOtp = () => {
        router.post(
            route("register.resend-otp")
        );
    };

    return (
        <>
            <Head title="Verify Email" />

            <div className={styles.verification}>
                {/* HEADER */}

                <header className={styles.header}>
                    <div
                        className={
                            styles.headerInner
                        }
                    >
                        <TextLink href="/">
                            <img
                                src={logo}
                                alt="TraderPlus"
                                className={
                                    styles.logo
                                }
                            />
                        </TextLink>

                        <TextLink
                            href="/register"
                        >
                            Back
                        </TextLink>
                    </div>
                </header>

                {/* CONTENT */}

                <main
                    className={
                        styles.content
                    }
                >
                    <div
                        className={
                            styles.wrapper
                        }
                    >
                        {/* COPY */}

                        <div
                            className={
                                styles.copy
                            }
                        >
                            <span>
                                EMAIL
                                VERIFICATION
                            </span>

                            <h1>
                                Verify your
                                email to continue
                            </h1>
                        </div>

                        {/* FLASHES */}

                        {flash?.success && (
                            <div
                                className={
                                    styles.successAlert
                                }
                            >
                                {
                                    flash.success
                                }
                            </div>
                        )}

                        {flash?.error && (
                            <div
                                className={
                                    styles.errorAlert
                                }
                            >
                                {
                                    flash.error
                                }
                            </div>
                        )}
                        <br />

                        {/* OTP */}

                        <div
                            className={
                                styles.codeInputs
                            }
                        >
                            {otpArray.map(
                                (
                                    digit,
                                    index
                                ) => (
                                    <input
                                        key={
                                            index
                                        }
                                        ref={(
                                            el
                                        ) => {
                                            inputs.current[
                                                index
                                            ] =
                                                el;
                                        }}
                                        type="text"
                                        inputMode="numeric"
                                        maxLength={
                                            1
                                        }
                                        value={
                                            digit ===
                                            " "
                                                ? ""
                                                : digit
                                        }
                                        onPaste={
                                            handlePaste
                                        }
                                        onKeyDown={(
                                            e
                                        ) =>
                                            handleKeyDown(
                                                e,
                                                index
                                            )
                                        }
                                        onChange={(
                                            e
                                        ) =>
                                            handleChange(
                                                e
                                                    .target
                                                    .value,
                                                index
                                            )
                                        }
                                    />
                                )
                            )}
                        </div>

                        <InputError
                            message={
                                errors.otp
                            }
                        />

                        {/* BUTTON */}

                        <Button
                            onClick={
                                verifyOtp
                            }
                            disabled={
                                processing ||
                                data.otp
                                    .length !==
                                    6
                            }
                            className={
                                styles.verifyButton
                            }
                        >
                            {processing && (
                                <LoaderCircle className="h-4 w-4 animate-spin" />
                            )}

                            Verify Email
                        </Button>

                        {/* FOOTER */}

                        <div
                            className={
                                styles.footerText
                            }
                        >
                            Didn't receive
                            the code?
                        </div>

                        <button
                            type="button"
                            onClick={
                                resendOtp
                            }
                            className={
                                styles.resend
                            }
                        >
                            Resend Code
                        </button>
                    </div>
                </main>
            </div>
        </>
    );
}