"use client";
import React, { useState, useEffect } from "react";
import { Text, Box, Image, Button, Stack, Divider, Title } 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 { IconEye, IconLogout, IconPhoneFilled, IconUsers, IconUserScreen } from "@tabler/icons-react";
import UserConfiguration from "./UserConfiguration";
import ViewUserConfiguration from "./ViewUserConfiguration";

export default function Login() {
    const router = useRouter();
    const [authorized, SetAuthorized] = useState<boolean | null>(null);
    const [view, setView] = useState<'userConf' | 'view' | null>(null);
    const [lastLoginDetails, setLastLoginDetails] = useState(null);
    const [name, setName] = useState(null);

    async function handleLogout(e: React.FormEvent) {
        e.preventDefault();
        localStorage.removeItem("admin_access_token");
        localStorage.clear();
        sessionStorage.clear();
        router.push("/administrator/login");
    }
    async function handleFetchUserDetails(e: React.FormEvent) {
        e.preventDefault();
        const token = localStorage.getItem("admin_access_token");
        const response = await fetch('/api/auth/admin/admin_details', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
        });
        const data = await response.json();
        // console.log(data)
        if (response.ok) {
            return data;
        }
        else if (response.status === 401 || data.message === 'invalid or expired token') {
            localStorage.removeItem("admin_access_token");
            router.push('/administrator/login');
        }
        else {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Please try again later",
                message: "Unable to fetch timestamp, please try again later",
                autoClose: 5000,
            });
        }
    }

    useEffect(() => {
        const token = localStorage.getItem("admin_access_token");
        if (!token) {
            SetAuthorized(false);
            router.push("/administrator/login/");
        } else {
            SetAuthorized(true);
            const fetchLoginTime = async () => {
                const result = await handleFetchUserDetails({ preventDefault: () => { } } as React.FormEvent);
                if (result) {
                    setLastLoginDetails(result.last_login);
                    setName(result.name);
                }
            };
            fetchLoginTime();
        }
    }, []);

    const handleClick = (type: 'UserConf' | 'ViewUser' | 'logout') => {
        if (type === 'UserConf') {
            setView('userConf');
        } else if (type === 'ViewUser') {
            setView('view');
        }
    };

    if (!authorized) return null;

    if (authorized) {
        return (
            <Providers>
                <div style={{ backgroundColor: "#f8f9fa", width: "100%", height: "100%", }}>
                    {/* Header */}
                    <Box
                        style={{
                            height: "60px",
                            position: 'relative',
                            width: '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: '6%',
                                color: 'White',
                                transition: "opacity 0.5s ease-in-out",
                            }}
                        >
                            THE KANGRA CENTRAL CO-OPERATIVE BANK LTD.
                        </Title>
                        <Text
                            style={{
                                position: 'absolute',
                                top: '50%',
                                left: '80%',
                                color: 'white',
                                textShadow: '1px 1px 2px black',
                            }}
                        >
                            <IconPhoneFilled size={20} /> Toll Free No : 1800-180-8008
                        </Text>
                    </Box>
                    {/* layout and */}
                    <Box style={{ display: 'flex', height: '90vh' }}>
                        {/* Sidebar manually placed under header */}
                        <Box
                            style={{
                                width: 250,
                                background: "#ebf5f5ff",
                                // background: "linear-gradient(90deg,rgba(42, 123, 155, 1) 0%, rgba(87, 199, 133, 1) 30%)",
                                padding: '1rem',
                                borderRight: '1px solid #ccc',
                            }}
                        >
                            <Title order={3} style={{ textAlign: 'center' }}>Admin Portal</Title>
                            <Divider my="xs" label="Menu" labelPosition="center" />
                            <Stack>
                                <Text td="underline" variant="light" style={{ cursor: 'pointer' }} onClick={() => handleClick('UserConf')}>
                                    <IconUsers size="15" /> User Configuration
                                </Text>
                                <Text td="underline" variant="light" style={{ cursor: 'pointer' }} onClick={() => handleClick('ViewUser')}>
                                    <IconEye size="15" /> View User Configuration
                                </Text>
                                <Text td="underline" variant="light" style={{ cursor: 'pointer' }} onClick={handleLogout}>
                                    <IconLogout size="15" /> Logout
                                </Text>
                            </Stack>
                        </Box>

                        {/* Main Content Area */}
                        <Stack style={{ flex: 1, padding: '1rem' }}>
                            <Box>
                                <Text c="Blue" size="lg" fs='italic'>Welcome ,{name} </Text>
                                <Text size="xs" c="gray" style={{ fontFamily: "inter", fontSize: '13px' }}>
                                    Last logged in at {lastLoginDetails ? new Date(lastLoginDetails).toLocaleString() : "N/A"}
                                </Text>
                            </Box>
                            <Box>
                                {view === 'userConf' && <UserConfiguration />}
                                {view === 'view' && <Text size="xl"><ViewUserConfiguration /></Text>}
                                {!view &&
                                    <Text size="xl">Welcome To The Admin Portal</Text>
                                }
                            </Box>
                        </Stack>
                    </Box>
                    <Divider size="xs" color='#99c2ff' />
                    <Text size="sm" style={{ textAlign: "center" }}>© 2025 The Kangra Central Co-Operative Bank</Text>
                </div>
            </Providers>
        );
    }
}
