"use client";
import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import axios from "axios";
import PageContainer from "@/app/components/container/PageContainer";
import {
    Box,
    Grid,
    Typography,
    Alert,
    LinearProgress,
    Button,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    TextField
} from "@mui/material";
import BaseCard from "../components/shared/BaseCard";
import { getSession } from "@/utils/sessionData";
import { DataGrid, GridRenderCellParams } from "@mui/x-data-grid";
import ApexArea from "./ApexArea";
import dayjs, { Dayjs } from "dayjs";

export default function KioskPage() {
    const router = useRouter();
    const [startDate, setStartDate] = useState<Dayjs>(dayjs().subtract(6, "day"));
    const [endDate, setEndDate] = useState<Dayjs>(dayjs());
    const [todaysDepositsGraph, setTodaysDepositsGraph] = useState<any>()

    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 [admins, setAdmins] = useState<any>([]);
    const [openAddModal, setOpenAddModal] = useState(false);
    const [newEmployee, setNewEmployee] = useState({
        first: "",
        last: "",
        email: "",
        phone: "",
        username: ""
    });
    // --- Update Balance Modal ---
    const [openBalanceModal, setOpenBalanceModal] = useState(false);
    const [balanceValue, setBalanceValue] = useState("");
    const [selectedAdminId, setSelectedAdminId] = useState<number | null>(null);

    // --- Delete Confirmation Modal ---
    const [openDeleteModal, setOpenDeleteModal] = useState(false);
    const [deleteAdminId, setDeleteAdminId] = useState<number | null>(null);
    const [todaysDeposits, setTodaysDeposits] = useState<any>({
        total_denomination: 0
    })
    // Clear alerts
    useEffect(() => {
        if (error || success) {
            const timer = setTimeout(() => {
                setError(null);
                setSuccess(null);
            }, 3000);
            return () => clearTimeout(timer);
        }
    }, [error, success]);

    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);
            } else {
                setError(response?.data?.message);
            }
        } catch (error: any) {
            setError(error?.message ?? "Unable to fetch admin");
        }
        setIsLoading(false);
    };

    const getAdmins = async () => {
        setIsLoading(true);
        try {
            const token = sessionData?.token ?? "";
            const response = await axios.post("/api/getAdmins", { token });

            if (response?.data?.status !== "error") {
                setAdmins(response?.data?.admins);
            } else {
                setError(response?.data?.message);
            }
        } catch (error: any) {
            setError(error?.message ?? "Unable to fetch admins");
        }
        setIsLoading(false);
    };

    useEffect(() => {
        checkSession();
    }, []);

    useEffect(() => {
        const session = getSession();
        setSessionData(session);
    }, []);

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



    useEffect(() => {
        if (user && user.role !== "Super") {
            router.push("/dashboard");
        }
    }, [user]);

    const fetchWagesChart = async () => {
        setIsLoading(true);
        try {
            const url = `api/wagesCharts`;

            const response = await axios.post(url, {
                from_date: startDate.format("YYYY-MM-DD"),
                to_date: endDate.format("YYYY-MM-DD")
            });

            if (response?.data?.status === "success") {
                setTodaysDepositsGraph({
                    labels: response.data.labels,
                    values: response.data.values
                });
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };
    return (
        <PageContainer title={"Employees - Emanage"} description="Employee Management">
            <Grid container spacing={2}>
                <Grid sx={{ width: { xs: "100%", lg: "100%" } }}>
                    {error && <Alert severity="error">{error}</Alert>}
                    {success && <Alert severity="success">{success}</Alert>}
                </Grid>

                <Grid sx={{ width: { xs: "100%", lg: "100%" } }}>
                    {isLoading && (
                        <>
                            <LinearProgress />
                            <br />
                        </>
                    )}
                    <ApexArea
                        graphData={todaysDepositsGraph}
                        startDate={startDate}
                        endDate={endDate}
                        setStartDate={setStartDate}
                        setEndDate={setEndDate}
                        onUpdate={fetchWagesChart}
                        isLoading={isLoading}
                    />
                </Grid>
            </Grid>


        </PageContainer>
    );
}
