"use client";

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

export default function ChangePassword() {
    const router = useRouter();

    // states
    const [oldPassword, setOldPassword] = useState("");
    const [newPassword, setNewPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [captcha, setCaptcha] = useState("");
    const [captchaInput, setCaptchaInput] = useState("");
    const [otp, setOtp] = useState("");
    const [generatedOtp, setGeneratedOtp] = useState("");
    const [otpValidated, setOtpValidated] = useState(false);
    const [countdown, setCountdown] = useState(180);
    const [timerActive, setTimerActive] = useState(false);
    const [step, setStep] = useState<"form" | "otp" | "final">("form");
    const icon = <IconLock size={18} stroke={1.5} />;

    // OTP generation
    // const handleGenerateOtp = async () => {
    //     const value = "123456"; // replace with backend OTP if available
    //     setGeneratedOtp(value);
    //     setCountdown(180);
    //     setTimerActive(true);
    //     return value;
    // };


    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;
        }
    }



    useEffect(() => {
        regenerateCaptcha();
    }, []);

    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]);

    // captcha
    const regenerateCaptcha = async () => {
        const newCaptcha = await generateCaptcha();
        setCaptcha(newCaptcha);
        setCaptchaInput("");
    };

    // password policy
    const validatePasswordPolicy = (password: string) => {
        return /^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,15}$/.test(
            password
        );
    };

    // handle submit
    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (step === "form") {
            if (!oldPassword || !newPassword || !confirmPassword || !captchaInput) {
                notifications.show({
                    title: "Missing Field",
                    message: "Please fill all mandatory fields.",
                    color: "red",
                });
                return;
            }
            if (!validatePasswordPolicy(newPassword)) {
                notifications.show({
                    title: "Invalid Password",
                    message:
                        "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.",
                    color: "red",
                });
                return;
            }
            if (newPassword !== confirmPassword) {
                notifications.show({
                    title: "Password Mismatch",
                    message: "Confirm password does not match new password.",
                    color: "red",
                });
                return;
            }
            if (captchaInput !== captcha) {
                notifications.show({
                    title: "Invalid Captcha",
                    message: "Please enter correct Captcha",
                    color: "red",
                });
                regenerateCaptcha();
                return;
            }

            await handleSendOtp();
            setStep("otp");
            notifications.show({
                title: "OTP Sent",
                message: "An OTP has been sent to your registered mobile.",
                color: "blue",
            });
            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;
        }

        if (step === "final") {
            const token = localStorage.getItem("access_token");
            if (!token) {
                router.push("/login");
                return;
            }
            try {
                const response = await fetch("/api/auth/change/login_password", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-Login-Type": "IB",
                        Authorization: `Bearer ${token}`,
                    },
                    body: JSON.stringify({
                        OldLPsw: oldPassword,
                        newLPsw: newPassword,
                        confirmLPsw: confirmPassword,
                    }),
                });

                if (response.status === 401) {
                    localStorage.clear();
                    sessionStorage.clear();
                    router.push("/login");
                    return;
                }

                const result = await response.json();
                if (!response.ok) {
                    notifications.show({
                        title: "Failed",
                        message: result.error || "Failed to change login password",
                        color: "red",
                        autoClose: false,
                    });
                    resetForm();
                } else {
                    notifications.show({
                        title: "Success",
                        message: "Login password changed successfully.",
                        color: "green",
                    });
                    resetForm();
                    router.push("/login");
                }
            } catch (err: any) {
                notifications.show({
                    title: "Error",
                    message: err.message || "Server error, please try again later",
                    color: "red",
                });
                resetForm();
            }
        }
    };

    const resetForm = () => {
        setOldPassword("");
        setNewPassword("");
        setConfirmPassword("");
        setCaptchaInput("");
        setOtp("");
        setOtpValidated(false);
        setStep("form");
        regenerateCaptcha();
    };

    return (
        <div
            style={{
                backgroundColor: "#f8f9fa",
                width: "100%",
                height: "auto",
                paddingTop: "5%",
            }}
        >
            {/* Header */}
            <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",
                    }}
                >
                    THE KANGRA CENTRAL CO-OPERATIVE BANK LTD.
                </Title>
            </Box>

            {/* Body */}
            <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" style={{ overflowY: "scroll" }}>
                        <Title order={3} ta="center" mb="md">
                            Change Password
                        </Title>
                        <form onSubmit={handleSubmit}>
                            <PasswordInput
                                label="Old Password"
                                placeholder="Enter old"
                                value={oldPassword}
                                onChange={(e) => setOldPassword(e.currentTarget.value)}
                                withAsterisk
                                readOnly={step !== "form"}
                            />
                            <PasswordInput
                                label="New Password"
                                placeholder="Enter new password"
                                value={newPassword}
                                onChange={(e) => setNewPassword(e.currentTarget.value)}
                                withAsterisk
                                readOnly={step !== "form"}
                            />
                            <PasswordInput
                                label="Confirm Password"
                                placeholder="Re-enter new password"
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.currentTarget.value)}
                                withAsterisk
                                rightSection={icon}
                                readOnly={step !== "form"}

                                onCopy={(e) => e.preventDefault()}
                                onPaste={(e) => e.preventDefault()}
                                onCut={(e) => e.preventDefault()}
                            />

                            {/* Captcha */}
                            {step === "form" && (
                                <Group mt="sm" align="center">
                                    <Box
                                        style={{
                                            backgroundColor: "#fff",
                                            fontSize: "18px",
                                            textDecoration: "line-through",
                                            padding: "4px 8px",
                                            fontFamily: "Verdana",
                                        }}
                                    >
                                        {captcha}
                                    </Box>
                                    <Button size="xs" variant="light" onClick={regenerateCaptcha}>
                                        Refresh
                                    </Button>
                                    <TextInput
                                        placeholder="Enter captcha"
                                        value={captchaInput}
                                        onChange={(e) => setCaptchaInput(e.currentTarget.value)}
                                        withAsterisk
                                    />
                                </Group>
                            )}

                            {/* OTP */}
                            {step !== "form" && (
                                <Box mt="sm">
                                    <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
                                            disabled={otpValidated}
                                            style={{ flex: 1 }}
                                        />
                                        {!otpValidated &&
                                            (timerActive ? (
                                                <Text size="xs" c="dimmed">
                                                    Resend OTP in{" "}
                                                    {String(Math.floor(countdown / 60)).padStart(2, "0")}:
                                                    {String(countdown % 60).padStart(2, "0")}
                                                </Text>
                                            ) : (
                                                <Button
                                                    variant="subtle"
                                                    px={8}
                                                    onClick={handleSendOtp}
                                                    leftSection={<IconRefresh size={16} />}
                                                >
                                                    Resend
                                                </Button>
                                            ))}
                                    </Group>
                                </Box>
                            )}

                            <Button type="submit" fullWidth mt="md" color="blue">
                                {step === "form" && "Submit"}
                                {step === "otp" && "Validate OTP"}
                                {step === "final" && "Change Password"}




                            </Button>
                        </form>

                        <Box mt="md">
                            <Text size="sm">
                                <strong>Note:</strong> Login 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>

            {/* Footer */}
            <Box
                style={{
                    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>
    );
}
