"use client";

import React, { useEffect, useState } from 'react';
import { Button, Input, Group, Stack, Text, Title, Box, Select, Paper, Switch } from '@mantine/core';
import { IconBuildingBank, IconEye, IconLink } from '@tabler/icons-react';
import { useRouter } from "next/navigation";
import { Providers } from "../../providers";
import { notifications } from '@mantine/notifications';
import dayjs from 'dayjs';

interface accountData {
    stAccountNo: string;
    stAccountType: string;
    stAvailableBalance: string;
    custname: string;
    activeAccounts: string;
}

export default function Home() {
    const [authorized, SetAuthorized] = useState<boolean | null>(null);
    const router = useRouter();
    const [accountData, SetAccountData] = useState<accountData[]>([]);
    const depositAccounts = accountData.filter(acc => acc.stAccountType !== "LN");
    const [selectedDA, setSelectedDA] = useState(depositAccounts[0]?.stAccountNo || "");
    const selectedDAData = depositAccounts.find(acc => acc.stAccountNo === selectedDA);
    const loanAccounts = accountData.filter(acc => acc.stAccountType === "LN");
    const [selectedLN, setSelectedLN] = useState(loanAccounts[0]?.stAccountNo || "");
    const selectedLNData = loanAccounts.find(acc => acc.stAccountNo === selectedLN);
    const [showBalance, setShowBalance] = useState(false);
    const PassExpiryRemains =(dayjs(localStorage.getItem("pswExpiryDate"))).diff(dayjs(),"day")

    // If back and forward button is clicked
    useEffect(() => {
        window.history.pushState(null, "", window.location.href);
        const handlePopState = () => {
            localStorage.removeItem("access_token");
            sessionStorage.removeItem("access_token");
            localStorage.removeItem("remitter_name");
            localStorage.removeItem("pswExpiryDate");
            localStorage.clear();
            sessionStorage.clear();
            router.push("/login");
        };
        // const handleBeforeUnload = () => {
        // // logout on tab close / refresh
        // localStorage.removeItem("access_token");
        // sessionStorage.removeItem("access_token");
        // localStorage.removeItem("remitter_name");
        // localStorage.removeItem("pswExpiryDate");
        // localStorage.clear();
        // sessionStorage.clear();
        // };
        window.addEventListener("popstate", handlePopState);
        // window.addEventListener("beforeunload", handleBeforeUnload);
        return () => {
            window.removeEventListener("popstate", handlePopState);
            // window.addEventListener("beforeunload", handleBeforeUnload);
        };
    }, []);

    async function handleFetchUserDetails() {
        try {
            const token = localStorage.getItem("access_token");
            const response = await fetch('api/customer', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            });
            const data = await response.json();
            if (response.ok && Array.isArray(data)) {
                SetAccountData(data);
                if (data.length > 0) {
                    const firstDeposit = data.find(acc => acc.stAccountType !== "LN");
                    const firstLoan = data.find(acc => acc.stAccountType === "LN");
                    if (firstDeposit) setSelectedDA(firstDeposit.stAccountNo);
                    if (firstLoan) setSelectedLN(firstLoan.stAccountNo);
                }
            } 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,
            });
        }
    }

    async function handleGetAccountStatement(accountNo: string) {
        router.push(`/accounts/account_statement?accNo=${accountNo}`);
    }

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

    useEffect(() => {
        if (authorized) {
            handleFetchUserDetails();
        }
    }, [authorized]);

    if (authorized) {
        return (
            <Providers>
                <div>
                    <Title order={4} style={{ padding: "10px" }}>Accounts Overview</Title>
                    <Group style={{ flex: 1, padding: "10px 10px 4px 10px", marginLeft: '10px', display: "flex", alignItems: "center", justifyContent: "left", height: "1vh" }}>
                        <IconEye size={20} />
                        <Text fw={700} style={{ fontFamily: "inter", fontSize: '17px' }}>Show Balance </Text>
                        <Switch size="md" onLabel="ON" offLabel="OFF" checked={showBalance}
                            onChange={(event) => setShowBalance(event.currentTarget.checked)} />
                    </Group>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-start", marginLeft: '15px' }}>
                        <Group grow gap="xl">
                            {/* Deposit Account Card */}
                            <Paper p="md" radius="md" style={{
                                backgroundColor: '#c1e0f0', width: 350, height: 195, display: 'flex',
                                flexDirection: 'column', justifyContent: 'space-between'
                            }}>
                                <Group gap='xs'>
                                    <IconBuildingBank size={25} />
                                    <Text fw={700}>Deposit Account</Text>
                                    {depositAccounts.length > 0 ? (
                                        <Select
                                            data={depositAccounts.map(acc => ({
                                                value: acc.stAccountNo,
                                                label: `${acc.stAccountType}- ${acc.stAccountNo}`
                                            }))}
                                            value={selectedDA}
                                            // @ts-ignore
                                            onChange={setSelectedDA}
                                            size="xs"
                                            styles={{
                                                input: {
                                                    backgroundColor: "white",
                                                    color: "black",
                                                    marginLeft: 5,
                                                    width: 140
                                                }
                                            }}
                                        />
                                    ) : (
                                        <Text c="dimmed" size="sm" ml="sm">No deposit account available</Text>
                                    )}
                                </Group>

                                {depositAccounts.length > 0 ? (
                                    <>
                                        <Text c="dimmed">{Number(selectedDAData?.stAccountNo || 0)}</Text>
                                        <Title order={2} mt="md">
                                            {showBalance ? `₹${Number(selectedDAData?.stAvailableBalance || 0).toLocaleString('en-IN')}` : "****"}
                                        </Title>
                                        <Button fullWidth mt="xs" onClick={() => handleGetAccountStatement(selectedDA)}>Get Statement</Button>
                                    </>
                                ) : (
                                    <>
                                        <Text c="dimmed" mt="md">Apply for a deposit account to get started</Text>
                                        <Button fullWidth mt="xs">Apply Now</Button>
                                    </>
                                )}
                            </Paper>

                            {/* Loan Account Card */}
                            <Paper p="md" radius="md" style={{
                                backgroundColor: '#c1e0f0', width: 355, height: 195, display: 'flex',
                                flexDirection: 'column', justifyContent: 'space-between'
                            }}
                            >
                                <Group gap='xs'>
                                    <IconBuildingBank size={25} />
                                    <Text fw={700}>Loan Account</Text>
                                    {loanAccounts.length > 0 ? (
                                        <Select
                                            data={loanAccounts.map(acc => ({
                                                value: acc.stAccountNo,
                                                label: `${acc.stAccountType}- ${acc.stAccountNo}`
                                            }))}
                                            value={selectedLN}
                                            // @ts-ignore
                                            onChange={setSelectedLN}
                                            size="xs"
                                            styles={{
                                                input: {
                                                    backgroundColor: "white",
                                                    color: "black",
                                                    marginLeft: 30,
                                                    width: 140
                                                }
                                            }}
                                        />
                                    ) : (
                                        <Text c="dimmed" size="sm" ml="sm">No loan account available</Text>
                                    )}
                                </Group>

                                {loanAccounts.length > 0 ? (
                                    <>
                                        <Text c="dimmed">{Number(selectedLNData?.stAccountNo || 0)}</Text>
                                        <Title order={2} mt="md">
                                            {showBalance ? `₹${Number(selectedLNData?.stAvailableBalance || 0).toLocaleString('en-IN')}` : "****"}
                                        </Title>
                                        <Button fullWidth mt="xs" onClick={() => handleGetAccountStatement(selectedLN)}>Get Statement</Button>
                                    </>
                                ) : (
                                    <>
                                        <Text c="dimmed" mt="md">Apply for a loan account to get started</Text>
                                        <Button fullWidth mt="xs">Apply Now</Button>
                                    </>
                                )}
                            </Paper>

                            {/* Important Links Card */}
                            <Paper p="md" radius="md" style={{ width: 300, backgroundColor: '#FFFFFF', marginLeft: '130px', border: '1px solid grey' }}>
                                <Title order={5} mb="sm">Quick Links </Title>
                                <Stack gap="xs">
                                    <Button variant="light" color="blue" fullWidth>Loan EMI Calculator</Button>
                                    <Button variant="light" color="blue" fullWidth>Branch Locator</Button>
                                    <Button variant="light" color="blue" fullWidth>Customer Care</Button>
                                    <Button variant="light" color="blue" fullWidth>FAQs</Button>
                                </Stack>
                            </Paper>
                        </Group>
                    </div>
                    <div style={{ padding: "20px", display: "flex", justifyContent: "left" }}>
                        <Stack>
                            <Text fw={700}> ** Book Balance includes uncleared effect.</Text>
                            <Text fw={700}> ** Click on the &quot;Show Balance&quot;to display balance for the Deposit and Loan account.</Text>
                            <Text fw={400} c="red"> ** Your Password will expire in {PassExpiryRemains} days.</Text>
                            <Text></Text>
                        </Stack>
                    </div>
                </div>
            </Providers>
        );
    }

    return null;
}