"use client";
import React, { useState, useEffect } from "react";
import { Text, Button, TextInput, PasswordInput, Title, Card, Group, Flex, Box, Image, Anchor, Stack, Popover, ActionIcon } 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/logo.jpg';
import frontPage from '@/app/image/ib_front_page.jpg';
import dynamic from 'next/dynamic';
import { generateCaptcha } from '@/app/captcha';

export default function Login() {
    const router = useRouter();
    const [error, setError] = useState<string | null>(null);
    const [CIF, SetCIF] = useState("");
    const [psw, SetPsw] = useState("");
    const [captcha, setCaptcha] = useState("");
    const [inputCaptcha, setInputCaptcha] = useState("");
    const [isLogging, setIsLogging] = useState(false);
    const ClientCarousel = dynamic(() => import('./clientCarousel'), { ssr: false });

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

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

    async function handleLogin(e: React.FormEvent) {
        e.preventDefault();
        const onlyDigit = /^\d{11}$/;
        if (!onlyDigit.test(CIF)) {
            setError('Input value must be 11 digit');
        }
        if (inputCaptcha !== captcha) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Captcha Error",
                message: "Please enter the correct captcha",
                autoClose: 5000,
            });
            return;
        }
        const response = await fetch('api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                customerNo: CIF,
                password: psw,
            }),
        });
        const data = await response.json();
        setIsLogging(true);
        if (response.ok) {
            console.log(data);
            const token = data.token;
            localStorage.setItem("access_token", token);
            if (data.FirstTimeLogin === true) {
                router.push("/ChangePassword")
            }
            else {
                router.push("/home");
            }

        }
        else {
            setIsLogging(false);
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Wrong User Id or Password",
                message: "Wrong User Id or Password",
                autoClose: 5000,
            });
        }
    }

    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(2, 163, 85, 1) 55%, rgba(101, 101, 184, 1) 100%)",
                    // border: "1px solid black"
                }}>
                    <Image
                        fit="cover"
                        src={logo}
                        component={NextImage}
                        alt="ebanking"
                        style={{ width: "40%", height: "100%", objectFit: "contain", marginLeft: 0 }}
                    />
                    <Text
                        style={{
                            position: 'absolute',
                            top: '50%',
                            left: '64%',
                            color: 'white',
                            textShadow: '1px 1px 2px blue',
                        }}
                    >
                        {/* <IconBuildingBank/> */}
                        Head Office : Dharmshala, District: Kangra(H.P), Pincode: 176215
                    </Text>
                </Box>
                <div style={{ marginTop: '10px' }}>
                    <Box
                        style={{
                            width: "100%",
                            height: "0.5%",
                            overflow: "hidden",
                            whiteSpace: "nowrap",
                            padding: "8px 0",
                        }}
                    >
                        <Text
                            component="span"
                            style={{
                                display: "inline-block",
                                paddingLeft: "100%",
                                animation: "scroll-left 60s linear infinite",
                                fontWeight: "bold",
                                color: "#004d99",
                            }}
                        >
                            ⚠️ Always login to our Net Banking site directly or through Banks website.
                            ⚠️ Do not disclose your UserId and Password to any third party and keep Your UserId and Password strictly confidential.
                            ⚠️ KCC Bank never asks for UserId,Passwords and Pins through email or  phone.
                            ⚠️ Be ware of Phishing mails with links to fake bank&apos;s websites asking for personal information are in circulation.
                            ⚠️ Please DO NOT Click on the links given in the emails asking for personal details like bank account number, userID and password.
                            ⚠️ If you had shard your UserId and Password through such mails or links, please change your Password immediately.
                            ⚠️ Inform the Bank/branch in which your account is maintained for resetting your password.
                        </Text>
                        <style>
                            {`
              @keyframes scroll-left {
                0% { transform: translateX(0%); }
                100% { transform: translateX(-100%); }
              }
            `}
                        </style>
                    </Box>
                    <div style={{ display: "flex", height: "75vh", overflow: "hidden", position: "relative" }}>
                        <div style={{ flex: 1, backgroundColor: "#c1e0f0", position: "relative" }}>
                            <Image
                                fit="cover"
                                src={frontPage}
                                component={NextImage}
                                alt="ebanking"
                                style={{ width: "100%", height: "100%" }}
                            />
                        </div>
                        <Card
                            shadow="lg"
                            padding="xl"
                            radius="md"
                            style={{
                                flex: 1,
                                display: "flex",
                                justifyContent: "center",
                                alignItems: "center",
                                backgroundColor: "#f0f0f0",
                                borderRadius: 0,
                                height: "100%",
                                boxShadow: "0 2px 10px rgba(228, 215, 215, 0.1)",
                                // border:"1px solid black"
                            }}
                        >
                            <Stack gap="xs" style={{ width: "100%", maxWidth: 480, marginTop: 0 }}>
                                <Title order={6} style={{ marginLeft: 10, marginBottom: "8px" }}>
                                    <Text fs="italic">Welcome To KCC Bank</Text>
                                    <Text fw={700} style={{ fontSize: "18px", color: "#000066" }}>Internet Banking</Text>
                                </Title>
                                <Box
                                    style={{
                                        // width: 370,
                                        marginTop: 0,
                                        // paddingTop: 5,
                                        padding: "10px",
                                        border: "1px solid #e0e0d1",
                                    }}
                                >
                                    <Flex justify="center" gap="md">
                                        <form onSubmit={handleLogin}>
                                            <TextInput
                                                size="md"
                                                label="User ID"
                                                placeholder="Enter your CIF No"
                                                type="text"
                                                inputMode="numeric"
                                                value={CIF}
                                                onInput={(e) => {
                                                    const input = e.currentTarget.value.replace(/\D/g, "");
                                                    if (input.length <= 11) {
                                                        SetCIF(input);
                                                    }
                                                }}
                                                required
                                                error={error}
                                            />

                                            <PasswordInput
                                                label="Password"
                                                size="md"
                                                placeholder="Enter your password"
                                                value={psw}
                                                onChange={(e) => SetPsw(e.currentTarget.value)}
                                                required
                                            />
                                            <Group mt="xs" align="center" gap="xs" >
                                                <Box
                                                    style={{
                                                        // padding: "5px",
                                                        alignItems: "center",
                                                        backgroundColor: "#fff",
                                                        fontFamily: "'UnifrakturCook',cursive",
                                                        // textDecoration: "line-through",
                                                        fontSize: "16px",
                                                        userSelect: "none",
                                                        display: "flex",
                                                        width: "30%"
                                                    }}
                                                >
                                                    {captcha}
                                                </Box>
                                                <Button variant="outline" size="xs" onClick={regenerateCaptcha}>
                                                    Refresh
                                                </Button>
                                            </Group>
                                            <TextInput
                                                label="Enter CAPTCHA"
                                                size="md"
                                                placeholder="Enter above text"
                                                value={inputCaptcha}
                                                onChange={(e) => setInputCaptcha(e.currentTarget.value)}
                                                required
                                            />
                                            <Button type="submit" disabled={isLogging} fullWidth variant="filled" mt="md">
                                                {/* Login */}
                                                {isLogging ? "Logging...." : "Login"}
                                            </Button>
                                        </form>
                                    </Flex>
                                </Box>
                            </Stack>
                        </Card>
                        {/* </div> */}
                    </div>
                    <Box style={{
                        width: "100%",
                        height: '50vh',
                        textAlign: "left",
                        marginTop: 10,
                        display: "flex",
                        // border: "1px solid blue"
                    }}>
                        <ClientCarousel />
                        <Box style={{ width: "40%", textAlign: "center" }}>
                            <Title order={2}>Security Notes :</Title>
                            <br></br>
                            <Text size="lg">When you Login,Your User Id and Password travels in an encrypted and highly secured mode .</Text>
                            <br></br>
                            <Text size="lg" fs="italic">For more information on Products and Services, Please Visit</Text>
                            <Text c="blue" td="underline">http://www.kccb.in/</Text>
                        </Box>
                    </Box>
                    <Box
                        component="footer"
                        style={{
                            width: "100%",
                            textAlign: "center",
                            padding: "10px 0",
                            bottom: 0,
                            left: 0,
                            zIndex: 1000,
                            fontSize: "14px",
                        }}
                    >
                        <Text>
                            © 2025 KCC Bank. All rights reserved. |{" "}
                            <Anchor href="document/disclaimer.pdf" target="_blank" rel="noopener noreferrer">Disclaimer</Anchor> |{" "}
                            <Anchor href="document/privacy_policy.pdf" target="_blank" rel="noopener noreferrer">Privacy Policy</Anchor> |{" "}
                            <Anchor href="document/phishing.pdf" target="_blank" rel="noopener noreferrer">Phishing</Anchor> |{" "}
                            <Anchor href="document/security_tips.pdf" target="_blank" rel="noopener noreferrer">Security Tips</Anchor> |{" "}
                            <Anchor href="document/grievance.jpg" target="_blank" rel="noopener noreferrer">Grievances</Anchor>
                        </Text>
                    </Box>
                </div>
            </div>
        </Providers>
    );
}
