"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/logo.jpg';
import { IconLogout, IconUsers, IconUserScreen } from "@tabler/icons-react";
import UserConfiguration from "./UserConfiguration";

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");
        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%", 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(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>
                    {/* layout and */}
                    <Box style={{ display: 'flex', height: '88vh' }}>
                        {/* Sidebar manually placed under header */}
                        <Box
                            style={{
                                width: 220,
                                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 /> User Configuration
                                </Text>
                                <Text td="underline" variant="light" style={{ cursor: 'pointer' }} onClick={() => handleClick('ViewUser')}>
                                    <IconUserScreen /> View Users
                                </Text>
                                <Text td="underline" variant="light" style={{ cursor: 'pointer' }} onClick={handleLogout}>
                                    <IconLogout /> 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">view</Text>}
                                {!view &&
                                    <Text size="xl">Welcome To The Admin Portal</Text>
                                }
                            </Box>
                        </Stack>
                    </Box>
                </div>
            </Providers>
        );
    }
}
