"use client";
import React, { useState } from "react";
import { Text, Button, TextInput, PasswordInput, Title, Card, Box, Image } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { Providers } from "@/app/providers";
import NextImage from "next/image";
import logo from '@/app/image/logo.jpg';
import changePwdImage from '@/app/image/changepw.png';
import { useRouter } from "next/navigation";
import { generateOTP } from '@/app/OTPGenerator';

export default function ValidateUser() {
    const router = useRouter();
    const [Cif, setCif] = useState("");
    const [otp, setOTP] = useState("");
    const [mobileNumber, setMobileNumber] = useState("");
    const [isCifValidated, setIsCifValidated] = useState(false);
    const [generateOtp, setGenerateOtp] = useState("");

    const validUsers = [
        { cif: "11111111111", mobile: "7890544527" },
        { cif: "30022497139", mobile: "6230573848" },
        { cif: "11122233344", mobile: "9998887776" },
    ];
    async function handleGenerateOtp() {
        // const value = await generateOTP(6);
        const value = "123456";
        setGenerateOtp(value);
        return value;
    }

    const handleValidateUser = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!Cif) {
            notifications.show({
                title: "Invalid CIF",
                message: "Please Enter your 11 digit CIF number.",
                color: "red",
            });
            setIsCifValidated(false);
            return;
        }
        if (!/^\d{11}$/.test(Cif)) {
            notifications.show({
                title: "Invalid CIF",
                message: "CIF number must be exactly 11 digits.",
                color: "red",
            });
            setIsCifValidated(false);
            return;
        }

        const user = validUsers.find((u) => u.cif === Cif);
        if (user) {
            setMobileNumber(user.mobile);
            setIsCifValidated(true);
            const Otp = await handleGenerateOtp();
            const masked = `xxxxxx${user.mobile.slice(-4)}`;
            notifications.show({
                title: "OTP Sent",
                message: `OTP sent to your registered mobile number ${masked}`,
                color: "green",
            });
        } else {
            setIsCifValidated(false);
            notifications.show({
                title: "User Not Found",
                message: "No such user is present.",
                color: "red",
            });
        }
    };

    const handleSubmitOtp = () => {
        if(!otp){
            notifications.show({
                title: "Invalid OTP",
                message: "Please Enter OTP Before You Submit.",
                color: "red",
            });
            return;
        }
        if (otp === generateOtp) {
            notifications.show({
                title: "OTP Verified",
                message: `OTP matched successfully`,
                color: "green",
            });
            router.push("/ForgetPassword")
        }
        else {
            setOTP("");
            notifications.show({
                title: "Invalid OTP",
                message: `The OTP you entered is incorrect`,
                color: "red",
            });
            return;
        }

    }

    return (
        <Providers>
            <div style={{ backgroundColor: "#f8f9fa", width: "100%", paddingTop: "5%" }}>
                <Box style={{
                    position: 'fixed', width: '100%', height: '15%', top: 0, left: 0, zIndex: 100,
                    display: "flex",
                    justifyContent: "flex-start",
                    background: "linear-gradient(15deg,rgba(2, 163, 85, 1) 55%, rgba(101, 101, 184, 1) 100%)"
                }}>
                    <Image fit="cover" src={logo} component={NextImage} alt="ebanking"
                        style={{ width: "100%", height: "100%" }} />
                </Box>
                <Box style={{ display: "flex", justifyContent: "center", alignItems: "center", columnGap: "5rem" }} bg="#c1e0f0">
                    <Image h="85vh" fit="contain" component={NextImage} src={changePwdImage} alt="Change Password Image" />
                    <Box h="100%" style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                        <Card p="xl" w="35vw" h="65vh" style={{ display: "flex", flexDirection: "column", justifyContent: "center" }}>
                            {/* @ts-ignore */}
                            <Title order={3} align="center" mb="md">Validate User</Title>

                            {isCifValidated && (
                                //  @ts-ignore
                                <Text align="center"> Welcome {" "}{Cif}</Text>
                            )}
                            <form onSubmit={(e)=>{
                                e.preventDefault();
                                isCifValidated?handleSubmitOtp():handleValidateUser(e);
                                }}>
                                <TextInput
                                    label="Enter Your CIF Number"
                                    placeholder="Enter your CIF"
                                    withAsterisk
                                    value={Cif}
                                    disabled={isCifValidated}
                                    onChange={(e) => {
                                        const input = e.currentTarget.value;
                                        if (input.length <= 11) {
                                            setCif(input);
                                        }
                                    }}
                                    onKeyDown={(e) => {
                                        const isNumberKey = /[0-9]/.test(e.key);
                                        const isControlKey = ["Backspace", "Tab", "ArrowLeft", "ArrowRight"].includes(e.key);
                                        if (!isNumberKey && !isControlKey) {
                                            e.preventDefault();
                                        }
                                    }}
                                />

                                <div style={{ marginTop: "1rem", minHeight: "80px" }}>
                                    {!isCifValidated && (
                                        <>
                                            <br></br>
                                            <Text fs="italic" c="dimmed">NOTE: Your CIF number travels in an encrypted and highly secured mode.</Text>
                                        </>
                                    )}
                                    {isCifValidated && (
                                        <>
                                            <PasswordInput
                                                label="Enter OTP"
                                                placeholder="Enter your OTP"
                                                withAsterisk
                                                value={otp}
                                                maxLength={6}
                                                onKeyDown={(e) => {
                                                    const isNumberKey = /[0-9]/.test(e.key);
                                                    const isControlKey = ["Backspace", "Tab", "ArrowLeft", "ArrowRight"].includes(e.key);
                                                    if (!isNumberKey && !isControlKey) {
                                                        e.preventDefault();
                                                    }
                                                }}
                                                onChange={(e) => setOTP(e.currentTarget.value)}
                                            />
                                            <Text size="xs" mt="xs" c='green'>
                                                OTP sent to your registered mobile number{" "}
                                                <b>{`xxxxxx${mobileNumber.slice(-4)}`}</b>
                                            </Text>
                                        </>
                                    )}
                                </div>

                                <Button type="submit" mt="lg" color="blue">
                                    {isCifValidated ? "Submit OTP" : "Validate"}
                                </Button>
                            </form>
                        </Card>
                    </Box>
                </Box>

                <Box
                    style={{
                        flexShrink: 0,
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center",
                        backgroundColor: "#f8f9fa",
                        marginTop: "0.5rem",
                    }}
                >
                    <Text c="dimmed" size="xs">
                        © 2025 Kangra Central Co-Operative Bank
                    </Text>
                </Box>

            </div>
        </Providers>
    );
}
