"use client";
import React, { useEffect, useState } from 'react';
import { Box, Button, Divider, Group, Image, 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';

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);

    async function handleLogout(e: React.FormEvent) {
        e.preventDefault();
        localStorage.removeItem("access_token");
        localStorage.removeItem("remitter_name");
        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;
                    localStorage.setItem("remitter_name", name);
                    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(() => {
        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");
            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>
                                </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>
        );
    }
}
