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

export default function Login() {
    const router = useRouter();
    const [error, setError] = useState<string | null>(null);
    const [userName, setUserName] = useState("");
    const [psw, SetPsw] = useState("");
    const [captcha, setCaptcha] = useState("");
    const [inputCaptcha, setInputCaptcha] = useState("");
    const [isLogging, setIsLogging] = useState(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();
        if (!userName || !psw || !captcha) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Field Blank",
                message: "Please enter all mandatory details",
                autoClose: 5000,
            });
            return;
        }
        if (inputCaptcha !== captcha) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Captcha Error",
                message: "Please enter the correct captcha",
                autoClose: 5000,
            });
            regenerateCaptcha();
            return;
        }
        const response = await fetch('/api/auth/admin/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                userName: userName,
                password: psw,
            }),
        });
        const data = await response.json();
        setIsLogging(true);
        if (response.ok) {
            console.log(data);
            const token = data.token;
            localStorage.setItem("admin_access_token", token);
            router.push("/administrator/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: "100%" }}>
                {/* Header */}
                <Box
                    component="header"
                    style={{
                        width: "100%",
                        padding: "0.8rem 2rem",
                        background: "linear-gradient(15deg, rgba(10, 114, 40, 1) 55%, rgba(101, 101, 184, 1) 100%)",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        color: "white",
                        boxShadow: "0 2px 6px rgba(0,0,0,0.15)",
                        position: "sticky",
                        top: 0,
                        zIndex: 100,
                    }}
                >
                    <Group gap="md">
                        <Image
                            src={logo}
                            component={NextImage}
                            fit="contain"
                            alt="ebanking"
                            style={{ width: "60px", height: "auto" }}
                        />
                        <div>
                            <Title order={3} style={{ fontFamily: "Roboto", color: "white", marginBottom: 2 }}>
                                THE KANGRA CENTRAL CO-OPERATIVE BANK LTD.
                            </Title>
                            <Text size="xs" c="white" style={{ opacity: 0.85 }}>
                                Head Office: Dharmshala, Kangra (H.P), Pin: 176215
                            </Text>
                        </div>
                    </Group>
                </Box>
                {/* Main */}
                <Box style={{
                    flex: 1,
                    position: "relative",
                    display: "flex",
                    justifyContent: "flex-end",
                    alignItems: "center",
                    overflow: "hidden",
                    background: 'linear-gradient(to right, #48ac64ff, #199444ff)'
                }}>
                    <Box style={{ flex: 1, backgroundColor: "#c1e0f0", position: "relative" }}>
                    <Image
                        fit="cover"
                        src={frontPage}
                        component={NextImage}
                        alt="ebanking"
                        style={{ width: "100%", height: "100%" }}
                    />
                    </Box>
                    <Box w={{ base: "100%", md: "50%" }} p="lg">
                        <Card shadow="md" padding="xl" radius="md" style={{ maxWidth: 500, margin: "0 auto", height: '70vh', backdropFilter: 'blur(8px)' }}>
                            {/* @ts-ignore */}
                            <Title order={3} align='center'>Admin Portal</Title>
                            <form onSubmit={handleLogin}>
                                <TextInput
                                    label="User Name"
                                    placeholder="Enter your user name"
                                    value={userName}
                                    onChange={(e) => setUserName(e.currentTarget.value)}
                                    error={error}
                                    withAsterisk
                                />
                                <PasswordInput
                                    label="Password"
                                    placeholder="Enter your password"
                                    value={psw}
                                    onChange={(e) => SetPsw(e.currentTarget.value)}
                                    withAsterisk
                                    mt="sm"
                                />
                                <Group mt="sm" align="center">
                                    <Box style={{ backgroundColor: "#fff", fontSize: "18px", textDecoration: "line-through", padding: "4px 8px", fontFamily: "cursive" }}>{captcha}</Box>
                                    <Button size="xs" variant="light" onClick={regenerateCaptcha}>Refresh</Button>

                                </Group>
                                <TextInput
                                    label="Enter CAPTCHA"
                                    placeholder="Enter above text"
                                    value={inputCaptcha}
                                    onChange={(e) => setInputCaptcha(e.currentTarget.value)}
                                    withAsterisk
                                    mt="sm"
                                />
                                <Button type="submit" fullWidth mt="md" disabled={isLogging}>
                                    {isLogging ? "Logging..." : "Login"}
                                </Button>
                            </form>
                        </Card>
                    </Box>
                </Box>
                {/* Footer */}
                <Box
                    component="footer"
                    style={{
                        width: "100%",
                        textAlign: "center",
                        fontSize: "12px",
                    }}
                >
                    <Text c='dimmed'>
                        © 2025 KCC Bank. All rights reserved.
                    </Text>
                </Box>

            </div>
        </Providers>
    );
}
