"use client";
import React, { useEffect, useState, useRef } 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/logo1.jpg';
import changePwdImage from '@/app/image/changepw.png';
import { useRouter } from "next/navigation";


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 headerRef = useRef<HTMLHeadingElement>(null);

    const validUsers = [
        { cif: "11111111111", mobile: "7890544528" },
        { cif: "30022497139", mobile: "6230573848" },
        { cif: "11122233344", mobile: "9998887776" },
    ];
    async function handleGenerateOtp() {
        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;
        }

    }

    useEffect(() => {
        const headerData = [
            "THE KANGRA CENTRAL CO-OPERATIVE BANK LTD.",
            "कांगड़ा केन्द्रीय सहकारी बैंक सीमित",
        ];
        let index = 0;
        const interval = setInterval(() => {
            index = (index + 1) % headerData.length;
            if (headerRef.current) {
                headerRef.current.textContent = headerData[index];
            }
        }, 2000);
        return () => clearInterval(interval);
    }, []);

    return (
        <Providers>
            <div style={{ backgroundColor: "#f8f9fa", width: "100%", paddingTop: "5%" }}>
                <Box
                    style={{
                        position: 'fixed', width: '100%', height: '12%', top: 0, left: 0, zIndex: 100,
                        display: "flex",
                        justifyContent: "flex-start",
                        background: "linear-gradient(15deg,rgba(10, 114, 40, 1) 55%, rgba(101, 101, 184, 1) 100%)",
                    }}>
                    <Image
                        src={logo}
                        component={NextImage}
                        fit="contain"
                        alt="ebanking"
                        style={{ width: "100%", height: "auto", flexShrink: 0 }}
                    />
                    <Title ref={headerRef}
                        order={2}
                        style={{
                            fontFamily: 'Roboto',
                            position: 'absolute',
                            top: '30%',
                            left: '7%',
                            color: 'White',
                            transition: "opacity 0.5s ease-in-out",
                        }}
                    >
                        THE KANGRA CENTRAL CO-OPERATIVE BANK LTD.
                    </Title>
                    <Text size="sm" c="white"
                        style={{
                            backgroundColor: '#1f1f14',
                            fontFamily: 'Roboto',
                            position: 'absolute',
                            top: '59%',
                            left: '72%',
                            color: 'white',
                            textShadow: '1px 1px 2px blue',
                        }}
                    >
                        Head Office : Dharmshala, District: Kangra(H.P), Pin: 176215
                    </Text>
                    {/* <Box style={{ position: "absolute", right: "1rem", top: "50%", transform: 'translateY(-50%)' }}>
                        <Tooltip
                            label='Head Office : Dharmshala, District: Kangra(H.P), Pin: 176215'
                            position="right"
                            withArrow>
                            <IconBuildingBank size={40} style={{ cursor: "pointer", color: "white" }} />
                        </Tooltip>
                    </Box> */}
                </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>
    );
}
