"use client";
import React, { useState, useEffect } from "react";
import { Text, Button, TextInput, PasswordInput, Title, Card, Box, Image, Group } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { Providers } from "@/app/providers";
import { useRouter } from "next/navigation";
import NextImage from "next/image";
import logo from '@/app/image/logo1.jpg';
import changePwdImage from '@/app/image/set_tran_pass.jpg';
import { generateCaptcha } from '@/app/captcha';
import { IconLock, IconLogout, IconRefresh } from '@tabler/icons-react';
import { sendOtp, verifyOtp } from "../_util/otp";



export default function SetTransactionPwd() {
    const router = useRouter();
    const [authorized, SetAuthorized] = useState<boolean | null>(null);
    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [captcha, setCaptcha] = useState("");
    const [captchaInput, setCaptchaInput] = useState("");
    const [captchaValidate, setCaptchaValidate] = useState(false);
    const [otp, setOtp] = useState("");
    const [countdown, setCountdown] = useState(60);
    const [timerActive, setTimerActive] = useState(false);
    const icon = <IconLock size={18} stroke={1.5} />;
    const [generateOtp, setGenerateOtp] = useState("");
    const [showOtpField, setShowOtpField] = useState(false);
    const [step, setStep] = useState<"form" | "otp" | "final">("form");
    const [otpValidated, setOtpValidated] = useState(false);




    async function handleSendOtp() {
        const mobileNumber = localStorage.getItem('remitter_mobile_no');
        if (!mobileNumber) {
            notifications.show({
                title: 'Error',
                message: 'Mobile number not found.Contact to administrator',
                color: 'red',
            });
            return;
        }
        try {
            await sendOtp({ type: 'CHANGE_LPWORD' });
            setCountdown(180);
            setTimerActive(true);
        } catch (err: any) {
            console.error('Send OTP failed', err);
            notifications.show({
                title: 'Error',
                message: err.message || 'Send OTP failed.Please try again later.',
                color: 'red',
            });
        }
    }

    async function handleVerifyOtp() {
        try {
            await verifyOtp(otp);
            return true;
        } catch {
            return false;
        }
    }

    async function handleGenerateOtp() {
        const value = "123456";
        setGenerateOtp(value);
        setCountdown(60);
        setTimerActive(true);
    }

    async function handleLogout(e: React.FormEvent) {
        e.preventDefault();
        localStorage.removeItem("access_token");
        localStorage.clear();
        sessionStorage.clear();
        router.push("/login")
    }
    const regenerateCaptcha = () => {
        const loadCaptcha = async () => {
            const newCaptcha = await generateCaptcha();
            setCaptcha(newCaptcha);
        };
        loadCaptcha();
        setCaptchaInput("");
    };

    useEffect(() => {
        const loadCaptcha = async () => {
            const newCaptcha = await generateCaptcha();
            setCaptcha(newCaptcha);
        };
        loadCaptcha();
    }, []);

    useEffect(() => {
        let interval: number | undefined;
        if (timerActive && countdown > 0) {
            interval = window.setInterval(() => {
                setCountdown((prev) => prev - 1);
            }, 1000);
        }
        if (countdown === 0) {
            if (interval) clearInterval(interval);
            setTimerActive(false);
        }
        return () => {
            if (interval) clearInterval(interval);
        };
    }, [timerActive, countdown]);

    async function handleSetTransactionPassword(e: React.FormEvent) {
        e.preventDefault();
        const pwdRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
        if (!password || !confirmPassword) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Field Required",
                message: "Both password fields are required.",
                autoClose: 5000,
            });
            return;
        }
        if (!captchaInput) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Field Required",
                message: "Please Enter Captcha details",
                autoClose: 5000,
            });
            return;
        }
        if (password !== confirmPassword) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Password Mismatch",
                message: "Passwords do not match.",
                autoClose: 5000,
            });
            return;
        }
        if (!pwdRegex.test(password)) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Invalid Password",
                message: "Password must contain at least one capital letter, one number, one special character, and be 8-15 characters long.",
                autoClose: 5000,
            });
            return;
        }
        if (captchaInput !== captcha) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Captcha Error",
                message: "Please enter the correct captcha",
                autoClose: 5000,
            });
            regenerateCaptcha();
            return;
        }
        if (!captchaValidate) {
            setCaptchaValidate(true);
            handleSendOtp();
            return;
        }
        if (!otp) {
            notifications.show({
                title: "Null Field",
                message: "Please enter the OTP",
                color: "red",
            });
            return;
        }

        // Step 2 → validate OTP
        if (step === "otp") {
            const verified = await handleVerifyOtp();
            if (!verified) {
                notifications.show({
                    title: "Invalid OTP",
                    message: "The OTP entered does not match",
                    color: "red",
                });
                return;
            }


            setOtpValidated(true);
            setStep("final");
            notifications.show({
                title: "OTP Verified",
                message: "OTP has been successfully verified.",
                color: "green",
            });
            return;


        }


        const token = localStorage.getItem("access_token");
        const response = await fetch('api/auth/transaction_password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Login-Type': 'IB',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                transaction_password: password,
            }),
        });
        const data = await response.json();
        if (response.ok) {
            // console.log(data);
            notifications.show({
                withBorder: true,
                color: "green",
                title: "Transaction Password has been set",
                message: "Transaction Password has been set",
                autoClose: 5000,
            });
            router.push("/login");
        }
        else {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Please try again later ",
                message: "Please try again later ",
                autoClose: 5000,
            });
            router.push("/login");
        }
    }
    useEffect(() => {
        const token = localStorage.getItem("access_token");
        if (!token) {
            SetAuthorized(false);
            router.push("/login");
        }
        else {
            SetAuthorized(true);
        }
    }, []);

    if (authorized) {
        return (
            <Providers>
                <div style={{ backgroundColor: "#f8f9fa", width: "100%", height: "auto", 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
                            fit="cover"
                            src={logo}
                            component={NextImage}
                            alt="ebanking"
                            style={{ width: "100%", height: "100%" }}
                        />
                        <Title
                            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>
                        <Button style={{
                            position: 'absolute',
                            top: '50%',
                            left: '90%',
                            color: 'white',
                            textShadow: '1px 1px 2px black',
                            fontSize: "20px"
                        }}
                            leftSection={<IconLogout color='white' />} variant="subtle" onClick={handleLogout}>Logout
                        </Button>
                    </Box>
                    <div>
                        <Box style={{ display: "flex", justifyContent: "center", alignItems: "center" }} bg="#80868989">
                            <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="40vw" h='85vh'>
                                    <Text onClick={() => router.push("/login")}
                                        style={{
                                            position: 'absolute', top: '1rem', right: '2rem', cursor: 'pointer', fontWeight: 500, color: '#7091ecff', textDecoration: 'underline'
                                        }}> Skip now</Text>

                                    <Title order={3}
                                        // @ts-ignore
                                        align="center" mb="md">Set Transaction Password</Title>
                                    <form onSubmit={handleSetTransactionPassword}>
                                        <PasswordInput
                                            label="Transaction Password"
                                            placeholder="Enter your Transaction password"
                                            withAsterisk
                                            id="loginPassword"
                                            value={password}
                                            onChange={(e) => setPassword(e.currentTarget.value)}
                                            onCopy={(e) => e.preventDefault()}
                                            onPaste={(e) => e.preventDefault()}
                                            onCut={(e) => e.preventDefault()}
                                            readOnly={captchaValidate}
                                        />
                                        <PasswordInput
                                            label="Confirm Transaction Password"
                                            placeholder="Re-enter your Transaction password"
                                            withAsterisk
                                            id="confirmPassword"
                                            rightSection={icon}
                                            value={confirmPassword}
                                            onChange={(e) => setConfirmPassword(e.currentTarget.value)}
                                            onCopy={(e) => e.preventDefault()}
                                            onPaste={(e) => e.preventDefault()}
                                            onCut={(e) => e.preventDefault()}
                                            readOnly={captchaValidate}
                                        />
                                        {/* CAPTCHA */}
                                        <Group mt="sm" align="center">
                                            <Box style={{
                                                backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "Verdana",
                                                userSelect: "none",
                                                pointerEvents: "none",
                                            }}
                                                onCopy={(e) => e.preventDefault()}
                                                onContextMenu={(e) => e.preventDefault()}>

                                                {captcha}</Box>
                                            <Button size="xs" variant="light" onClick={regenerateCaptcha}>Refresh</Button>
                                        </Group>
                                        <TextInput
                                            label="Enter CAPTCHA"
                                            placeholder="Enter above text"
                                            value={captchaInput}
                                            onChange={(e) => setCaptchaInput(e.currentTarget.value)}
                                            withAsterisk
                                            mt="sm"
                                            readOnly={captchaValidate}
                                        />
                                        <Box style={{ height: 60 }}>
                                            {captchaValidate && (
                                                <Group gap="xs" align="flex-end">
                                                    <PasswordInput
                                                        label="Enter OTP"
                                                        placeholder="Enter the OTP"
                                                        value={otp}
                                                        maxLength={6}
                                                        onChange={(e) => setOtp(e.currentTarget.value)}
                                                        withAsterisk
                                                        style={{ flex: 1 }}
                                                    />
                                                    {timerActive ? (
                                                        <Text size="xs" c="dimmed">
                                                            Resend OTP will be enabled in 00:{countdown < 10 ? `0${countdown}` : countdown} min
                                                        </Text>
                                                    ) : (
                                                        <Button
                                                            variant="subtle"
                                                            px={8}
                                                            onClick={handleSendOtp}
                                                            leftSection={<IconRefresh size={16} />}
                                                        >
                                                            Resend
                                                        </Button>
                                                    )}
                                                </Group>
                                            )}
                                        </Box>
                                        <Button
                                            type="submit"
                                            fullWidth
                                            mt="sm"
                                            color="blue"
                                        >
                                            Set
                                        </Button>
                                    </form>
                                    <br></br>
                                    <Box
                                        style={{
                                            flex: 1,
                                            borderLeft: '1px solid #ccc',
                                            paddingLeft: 16,
                                            minHeight: 90,

                                        }}
                                    >
                                        <Text size="sm">
                                            <strong>Note:</strong> Password must contain at least one capital letter(A-Z), one digit(0-9), one special symbol(e.g.,@,#,$), and be 8-15 characters long.
                                        </Text>
                                    </Box>
                                </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>
                </div>
            </Providers >
        );
    }
}
