"use client";
import React, { useEffect, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import axios from "axios";
import PageContainer from "../../app/components/container/PageContainer";
import { Box, Grid, Typography, Card, CardContent, Alert, CircularProgress, LinearProgress, Button } from "@mui/material";
import Image from "next/image";
import TopCardsNew from "../components/dashboards/modern/TopCardsNew";
import ApexArea from "./ApexArea";
import ApexArea2 from "./ApexArea2";
import TopCardsNew2 from "../components/dashboards/modern/TopCardsNew2";

import dayjs, { Dayjs } from "dayjs";
import BaseCard from "../components/shared/BaseCard";
import { getSession } from '../../utils/sessionData';
import moment from "moment-timezone";
import { DataGrid } from "@mui/x-data-grid";

export default function KioskPage() {

    const router = useRouter();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [sessionData, setSessionData] = useState<any>();
    const [user, setUser] = useState<any>();
    const [actionLoading, setActionLoading] = useState<any>(null);

    const checkSession = async () => {
        const session = getSession()
        if (!session?.admin_id && !session?.token) {
            router.push('/login')
        }
    }
    const getAdmin = async () => {
        setIsLoading(true);
        try {
            const token = sessionData?.token ?? '';
            const response = await axios.post('/api/getAdmin', { token })
            if (response?.data?.status !== 'error') {
                setUser(response?.data?.admin)
                setIsLoading(false);

            } else {
                setError(response?.data?.message)
                console.log(response?.data?.message)
                setIsLoading(false);

            }
        } catch (error: any) {
            setError(error?.message ?? 'Unable to fetch admin')
            setIsLoading(false);

        }
    }
    useEffect(() => {
        if (error || success) {
            const timer = setTimeout(() => {
                setError(null);
                setSuccess(null);
            }, 3000);
            return () => clearTimeout(timer);
        }
    }, [error, success]);
    useEffect(() => {
        checkSession()
    }, [])
    useEffect(() => {
        const session = getSession();
        setSessionData(session);
    }, []);

    useEffect(() => {
        if (sessionData?.token) {
            getAdmin()
        }
    }, [sessionData?.token, sessionData?.admin_id])

    function formatWithMoment(datetime: any) {
        return moment(datetime, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD h:mm A");
    }

    const handleLoginLogout = async (type: any) => {
        setActionLoading(type);
        setIsLoading(true);

        try {
            const id = sessionData?.admin_id ?? '';
            const token = sessionData?.token ?? '';
            const user_agent = navigator.userAgent;
            const screen_width = window.innerWidth;

            const payload = {
                user_agent,
                screen_width,
                token
            }
            if (type == 'login') {
                const response = await axios.post('/api/handleLogout', payload)
                if (response?.data?.status !== 'error') {
                    setSuccess('Logout successful')
                    getAdmin();
                    setIsLoading(false);

                } else {
                    setError(response?.data?.message ?? 'Logout failed')
                    setIsLoading(false);

                }
            } else {
                const response = await axios.post('/api/handleLogin', payload)
                if (response?.data?.status !== 'error') {
                    setSuccess('Login successful')
                    getAdmin();
                    setIsLoading(false);

                } else {
                    setError(response?.data?.message ?? 'Login failed')
                    setIsLoading(false);

                }
            }
        } catch (error: any) {
            setError(error?.message ?? 'Unknown error')
            setIsLoading(false);

        } finally {
            setActionLoading(null);     // stop loading
        }
    }
    const rows =
        user?.logs?.map((log: any, index: any) => ({
            id: index + 1,
            time: formatWithMoment(log.logtime),
            type: log.type === 1 ? "Login" : "Logout",
            typeColor: log.type === 1 ? "green" : "crimson",
        })) || [];

    // DataGrid columns
    const columns = [
        {
            field: "time",
            headerName: "Time",
            flex: 1,
            minWidth: 150,
            renderCell: (params: any) => (
                <span style={{ fontWeight: 600 }}>{params.value}</span>
            ),
        },
        {
            field: "type",
            headerName: "Type",
            flex: 1,
            minWidth: 120,
            renderCell: (params: any) => (
                <span
                    style={{
                        fontWeight: 700,
                        color: params.row.typeColor,
                    }}
                >
                    {params.value}
                </span>
            ),
        },
    ];
    return (
        <PageContainer title={'Dashboard - Emanage'} description="Kiosk details">
            <Grid container spacing={2}>
                {/* {isLoading && <LinearProgress />} */}
                <Grid sx={{ width: { xs: '100%', lg: '100%' } }}>
                    {error && <Alert severity="error" onClose={() => setError(null)}>{error}</Alert>}
                    {success && <Alert severity="success" onClose={() => setSuccess(null)}>{success}</Alert>}
                </Grid>
                <Grid sx={{ width: { xs: "100%", lg: "50%" } }}>
                    <BaseCard title="Signin / Signout">
                        <Box
                            sx={{
                                display: "flex",
                                flexDirection: { xs: "column", lg: "row" }, // mobile = column, desktop = row
                                justifyContent: "space-between",
                                alignItems: { xs: "flex-start", lg: "center" },
                                gap: 2,
                                py: 1,
                                // borderBottom: "1px solid #eee",
                            }}
                        >
                            {/* LEFT — TEXT */}
                            <Typography fontWeight={600}>
                                {user && user.latest_login ? (
                                    user.latest_login.type == 1
                                        ? `Login Time: ${formatWithMoment(user.latest_login.logtime)}`
                                        : `Logout Time: ${formatWithMoment(user.latest_login.logtime)}`
                                ) : (
                                    "..."
                                )}
                            </Typography>

                            {/* RIGHT — BUTTON */}
                            <Button
                                sx={{
                                    width: { xs: "100%", lg: "auto" },
                                    fontWeight: "bold",
                                    px: 4,
                                    backgroundColor:
                                        user?.latest_login?.type == 1 ? "crimson" : "green",
                                    color: "#fff",
                                    "&:hover": {
                                        backgroundColor:
                                            user?.latest_login?.type == 1 ? "crimson" : "#007700",
                                    },
                                    alignSelf: { xs: "stretch", lg: "center" },
                                }}
                                onClick={() =>
                                    handleLoginLogout(
                                        user?.latest_login?.type == 1 ? "login" : "logout"
                                    )
                                }
                                disabled={isLoading || actionLoading !== null}
                            >
                                {
                                    actionLoading
                                        ? actionLoading === "login"
                                            ? "Logging out..."
                                            : "Logging in..."
                                        : user?.latest_login?.type == 1
                                            ? "Logout"
                                            : "Login"
                                }
                            </Button>
                        </Box>
                    </BaseCard>
                </Grid>
                <Grid sx={{ width: { xs: '100%', lg: '50%' } }}>
                    <BaseCard
                        title={`Logs for ${moment().tz("America/Denver").format("YYYY-MM-DD")}`}
                    >
                        <Box sx={{ height: 400, width: "100%" }}>
                            {rows.length > 0 ? (
                                <DataGrid
                                    rows={rows}
                                    columns={columns}
                                    pageSizeOptions={[5, 10, 20]}
                                    initialState={{
                                        pagination: { paginationModel: { pageSize: 5 } },
                                    }}
                                    sx={{
                                        border: "none",

                                        /* remove blue cell outline */
                                        "& .MuiDataGrid-cell:focus": {
                                            outline: "none !important",
                                        },
                                        "& .MuiDataGrid-cell:focus-within": {
                                            outline: "none !important",
                                        },

                                        /* remove blue row outline */
                                        "& .MuiDataGrid-row:focus": {
                                            outline: "none !important",
                                        },
                                        "& .MuiDataGrid-row:focus-within": {
                                            outline: "none !important",
                                        },

                                        /* remove selected row highlight */
                                        // "& .MuiDataGrid-row.Mui-selected": {
                                        //     backgroundColor: "transparent !important",
                                        // },
                                        // "& .MuiDataGrid-row.Mui-selected:hover": {
                                        //     backgroundColor: "transparent !important",
                                        // },

                                        /* remove column header focus outline */
                                        "& .MuiDataGrid-columnHeader:focus": {
                                            outline: "none !important",
                                        },
                                        "& .MuiDataGrid-columnHeader:focus-within": {
                                            outline: "none !important",
                                        },

                                        "& .MuiDataGrid-columnHeaders": {
                                            backgroundColor: "#f8f8f8",
                                            fontWeight: "bold",
                                            fontSize: "14px",
                                        },
                                        "& .MuiDataGrid-cell": {
                                            fontSize: "14px",
                                        },
                                    }}
                                />
                            ) : (
                                <Typography sx={{ p: 2 }}>No logs found</Typography>
                            )}
                        </Box>
                    </BaseCard>
                    {/* <BaseCard
                        title={`Logs for ${moment().tz("America/Denver").format("YYYY-MM-DD")}`}
                    >
                        <Box sx={{ p: 1 }}>
                            {user && user.logs && user.logs.length > 0 ? (
                                user.logs.map((log: { logtime: any; type: number; }, index: React.Key | null | undefined) => (
                                    <Grid
                                        key={index}
                                        container
                                        justifyContent="space-between"
                                        alignItems="center"
                                        sx={{
                                            py: 1,
                                            borderBottom: "1px solid #eee",
                                        }}
                                    >
                                       
                                        <Grid >
                                            <Typography fontWeight={600}>
                                                {formatWithMoment(log.logtime)}
                                            </Typography>
                                        </Grid>

                                        
                                        <Grid >
                                            <Typography
                                                fontWeight={700}
                                                sx={{
                                                    color: log.type == 1 ? "green" : "red",
                                                }}
                                            >
                                                {log.type == 1 ? "Login" : "Logout"}
                                            </Typography>
                                        </Grid>
                                    </Grid>
                                ))
                            ) : (
                                <Typography>No logs found</Typography>
                            )}
                        </Box>
                    </BaseCard> */}
                </Grid>
            </Grid>
        </PageContainer >
    );
}
