"use client";
import React, { useEffect, useState } from 'react';
import { Box, Button, Divider, Group, Image, Popover, Stack, Text, Title } from '@mantine/core';
import { IconBook, IconCurrencyRupee, IconHome, IconLogout, IconPhoneFilled, IconSettings } from '@tabler/icons-react';
import Link from 'next/link';
import { useRouter, usePathname } from "next/navigation";
import { Providers } from '../providers';
import logo from '@/app/image/logo1.jpg';
import NextImage from 'next/image';
import { notifications } from '@mantine/notifications';
import { useDisclosure } from '@mantine/hooks';

export default function RootLayout({ children }: { children: React.ReactNode }) {
    const router = useRouter();
    const pathname = usePathname();
    const [authorized, SetAuthorized] = useState<boolean | null>(null);
    const [userLastLoginDetails, setUserLastLoginDetails] = useState(null);
    const [custname, setCustname] = useState<string | null>(null);


    const [opened, { open, close }] = useDisclosure(false);

    function doLogout() {
        localStorage.removeItem("access_token");
        sessionStorage.removeItem("access_token");
        localStorage.removeItem("remitter_name");
        localStorage.removeItem("pswExpiryDate");
        localStorage.clear();
        sessionStorage.clear();
        router.push("/login");
    }

    async function handleLogout(e: React.FormEvent) {
        e.preventDefault();
        doLogout()
        router.push("/login");
    }

    async function handleFetchUserName() {
        try {
            const token = localStorage.getItem("access_token");
            const response = await fetch('/api/customer', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            });
            if (!response.ok) {
                notifications.show({
                    withBorder: true,
                    color: "red",
                    title: "Error",
                    message: "Internal Server Error",
                    autoClose: 5000,
                });
                localStorage.removeItem("access_token");
                localStorage.removeItem("remitter_name");
                return;
            }
            const data = await response.json();
            if (response.ok && Array.isArray(data)) {
                if (data.length > 0) {
                    const name = data[0].custname;
                    const mobileNumber = data[0].mobileno;
                    localStorage.setItem("remitter_name", name);
                    localStorage.setItem("remitter_mobile_no", mobileNumber);
                    setCustname(name);
                }
            } else {
                throw new Error();
            }
        } catch {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Please try again later",
                message: "Unable to Fetch, Please try again later",
                autoClose: 5000,
            });
        }
    }
    useEffect(() => {
        // Push fake history state to trap navigation
        window.history.pushState(null, "", window.location.href);
        const handlePopState = () => {
            doLogout(); // logout when back/forward pressed
        };
        const handleBeforeUnload = (e: BeforeUnloadEvent) => {
            // logout on tab close / refresh
            localStorage.removeItem("access_token");
            sessionStorage.removeItem("access_token");
            localStorage.clear();
            sessionStorage.clear();
        };
        window.addEventListener("popstate", handlePopState);
        window.addEventListener("beforeunload", handleBeforeUnload);
        return () => {
            window.removeEventListener("popstate", handlePopState);
            window.addEventListener("beforeunload", handleBeforeUnload);
        };
    }, []);

    useEffect(() => {
        const token = localStorage.getItem("access_token");
        if (!token) {
            SetAuthorized(false);
            router.push("/login");
        }
        else {
            SetAuthorized(true);
            handleFetchUserName();
        }
    }, []);

    async function handleFetchUserDetails(e: React.FormEvent) {
        e.preventDefault();
        const token = localStorage.getItem("access_token");
        const response = await fetch('/api/auth/user_details', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
        });
        const data = await response.json();
        if (response.ok) {
            return data;
        }
        else if (response.status === 401 || data.message === 'invalid or expired token') {
            // console.log(data);
            localStorage.removeItem("access_token");
            localStorage.clear();
            sessionStorage.clear();
            router.push('/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 fetchLoginTime = async () => {
            const result = await handleFetchUserDetails({ preventDefault: () => { } } as React.FormEvent);
            if (result) {
                setUserLastLoginDetails(result.last_login);
            }
        };
        fetchLoginTime();
    }, []);

    const navItems = [
        { href: "/home", label: "Home", icon: IconHome },
        { href: "/accounts", label: "Accounts", icon: IconBook },
        { href: "/funds_transfer", label: "Send Money", icon: IconCurrencyRupee },
        { href: "/settings", label: "Settings", icon: IconSettings },
    ];

    if (authorized) {
        return (
            <html lang="en">
                <body>
                    <Providers>
                        <div style={{ backgroundColor: "#e6ffff", height: "100vh", display: "flex", flexDirection: "column", padding: 0, margin: 0 }}>
                            <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>

                            <div
                                style={{
                                    flexShrink: 0,
                                    padding: '0.5rem 1rem',
                                    display: "flex",
                                    justifyContent: 'space-between',
                                    alignItems: "center",
                                }}
                            >
                                <Stack gap={0} align="flex-start">
                                    <Title order={4} style={{ fontFamily: "inter", fontSize: '22px' }}>
                                        Welcome, {custname ?? null}
                                    </Title>
                                    <Text size="xs" c="gray" style={{ fontFamily: "inter", fontSize: '13px' }}>
                                        Last logged in at {userLastLoginDetails ? new Date(userLastLoginDetails).toLocaleString() : "N/A"}
                                    </Text>
                                </Stack>

                                <Group mt="md" gap="sm">
                                    {navItems.map((item) => {
                                        const isActive = pathname.startsWith(item.href);
                                        const Icon = item.icon;
                                        return (
                                            <Link key={item.href} href={item.href}>
                                                <Button
                                                    leftSection={<Icon size={20} />}
                                                    variant={isActive ? "dark" : "subtle"}
                                                    color={isActive ? "blue" : undefined}
                                                >
                                                    {item.label}
                                                </Button>
                                            </Link>
                                        );
                                    })}
                                    {/* <Button leftSection={<IconLogout size={20} />} variant="subtle" onClick={handleLogout}>
                                        Logout
                                    </Button> */}
                                    <Popover
                                        opened={opened}
                                        onChange={close}
                                        position="bottom-end"   // 👈 Logout button ke niche right align
                                        withArrow
                                        shadow="md"
                                    >
                                        <Popover.Target>
                                            <Button
                                                leftSection={<IconLogout size={20} />}
                                                variant="subtle"
                                                onClick={open}
                                            >
                                                Logout
                                            </Button>
                                        </Popover.Target>

                                        <Popover.Dropdown>
                                            <Text size="sm" mb="sm">
                                                Are you sure you want to logout?
                                            </Text>
                                            <Group justify="flex-end" gap="sm">
                                                <Button variant="default" onClick={close}>
                                                    Cancel
                                                </Button>
                                                <Button onClick={handleLogout}>
                                                    Logout
                                                </Button>
                                            </Group>
                                        </Popover.Dropdown>
                                    </Popover>
                                </Group>
                            </div>

                            <Divider size="xs" color='#99c2ff' />

                            <div
                                style={{
                                    flex: 1,
                                    overflowY: "auto",
                                    borderTop: '1px solid #ddd',
                                    borderBottom: '1px solid #ddd',
                                }}
                            >
                                {children}
                            </div>

                            <Divider size="xs" color='blue' />

                            <Box
                                style={{
                                    flexShrink: 0,
                                    display: "flex",
                                    justifyContent: "center",
                                    alignItems: "center",
                                    backgroundColor: "#f8f9fa",
                                    marginTop: "0.5rem",
                                }}
                            >
                                <Text c="dimmed" size="xs">
                                    © 2025 The Kangra Central Co-Operative Bank
                                </Text>
                            </Box>
                        </div>
                    </Providers>
                </body>
            </html >
        );
    }
}
