"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 } 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";
export default function KioskPage() {
    const searchParams = useSearchParams();
    const router = useRouter();
    const kioskId = searchParams?.get("kioskId") ?? searchParams?.get("kiosk_id");

    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [kioskData, setKioskData] = useState<any>({
        amountStacked: 0,
        notesStacked: 0

    });
    const [kioskF53Data, setKioskF53Data] = useState<any>();
    const [error, setError] = useState<string | null>(null);
    const [sessionData, setSessionData] = useState<any>();
    // const [isLoading, setIsLoading] = useState(false);
    const [kioskRunning, setKioskRunning] = useState<any>(false);
    const [kioskF53Running, setKioskF53Running] = useState<any>(false);
    const [todaysDeposits, setTodaysDeposits] = useState<any>({
        total_denomination: 0
    })
    const [todaysDepositsGraph, setTodaysDepositsGraph] = useState<any>()
    const [todaysCashOutGraph, setTodaysCashOutGraph] = useState<any>()

    const [todaysCashouts, setTodaysCashouts] = useState<any>()
    const [startDate, setStartDate] = useState<Dayjs>(dayjs().subtract(6, "day"));
    const [startDate2, setStartDate2] = useState<Dayjs>(dayjs().subtract(6, "day"));

    const [endDate, setEndDate] = useState<Dayjs>(dayjs());
    const [endDate2, setEndDate2] = useState<Dayjs>(dayjs());

    // Use the same getSession util you used on Dashboard
    const getSessionData = () => {
        try {
            // client-side require to keep same behaviour as Dashboard
            // (or import if you already import it at top)
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { getSession } = require('@/utils/sessionData');
            return getSession();
        } catch (e) {
            return null;
        }
    };
    const [dashData, setDashData] = useState<any>({
        totalDeposit: 0,
        billCount: 0,
        balance: 0
    })

    const fetchTodaysDeposits = async () => {
        setIsLoading(true)
        try {
            const kioskName = sessionStorage?.getItem('kioskName') ?? ''
            const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}/kiosk/getTodayDeposits?kiosk_name=${kioskName}`;
            const response = await axios.get(url, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            if (response?.data?.status !== 'error') {
                setTodaysDeposits(response?.data?.data3)
                // setTodaysDepositsGraph(response?.data?.data2)
                setIsLoading(false)
            } else {
                console.log(response?.data)
                setIsLoading(false)

            }
        } catch (error: any) {
            console.log(error?.message)
            setIsLoading(false)

        }
    }
    const fetchTodaysCashouts = async () => {
        setIsLoading(true)
        try {
            const kioskName = sessionStorage?.getItem('kioskName') ?? ''
            const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}/kiosk/getTodayCashouts?kiosk_name=${kioskName}`;
            const response = await axios.get(url, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            if (response?.data?.status !== 'error') {
                setTodaysCashouts(response?.data?.data)
                console.log(response?.data?.data)
                // setTodaysDepositsGraph(response?.data?.data2)
                setIsLoading(false)
            } else {
                console.log(response?.data)
                setIsLoading(false)

            }
        } catch (error: any) {
            console.log(error?.message)
            setIsLoading(false)

        }
    }
    const fetchDailyDeposits = async (from: Dayjs, to: Dayjs) => {
        setIsLoading(true);
        try {
            const kioskName = sessionStorage?.getItem("kioskName") ?? "";
            const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}/kiosk/getDayWiseDeposits`;

            const response = await axios.get(url, {
                params: {
                    kiosk_name: kioskName,
                    startUtc: from.startOf("day").toISOString(),
                    endUtc: to.endOf("day").toISOString(),
                },
            });
            if (response?.data?.status === "success") {
                setTodaysDepositsGraph(response.data.data);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };
    const fetchDailyCashouts = async (from: Dayjs, to: Dayjs) => {
        setIsLoading(true);
        try {
            const kioskName = sessionStorage?.getItem("kioskName") ?? "";
            const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}/kiosk/getDayWiseCashouts`;

            const response = await axios.get(url, {
                params: {
                    kiosk_name: kioskName,
                    startUtc: from.startOf("day").toISOString(),
                    endUtc: to.endOf("day").toISOString(),
                },
            });
            if (response?.data?.status === "success") {
                setTodaysCashOutGraph(response.data.data);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };
    useEffect(() => {
        fetchTodaysDeposits()
        fetchTodaysCashouts()
        fetchDailyDeposits(startDate, endDate)
        fetchDailyCashouts(startDate2, endDate2)

    }, [kioskId, router])
    useEffect(() => {
        if (!kioskId) {
            setError("No kiosk selected. Please go back and select a kiosk.");
            return;
        }

        const session = getSessionData();
        if (!session?.token) {
            router.push("/login");
            return;
        }

        let isMounted = true;

        (async () => {
            setIsLoading(true);
            setError(null);

            try {
                const token = session.token;
                const kioskName = sessionStorage.getItem("kioskName") ?? "";

                // start both requests concurrently
                const dashboardReq = axios.post(`/api/getDashboardData`, { token, kioskId });
                const kioskReq = axios.post(`/api/getKioskStatus`, { token, kioskName });
                const kioskF53Req = axios.post(`/api/getF53Status`, { token, kioskName });

                // Use Promise.allSettled so one failure doesn't cancel the other
                const [dashRes, kioskRes, kioskF53Res] = await Promise.allSettled([dashboardReq, kioskReq, kioskF53Req]);

                if (!isMounted) return;

                // handle dashboard result
                if (dashRes.status === "fulfilled") {
                    const resp = dashRes.value;
                    if (resp?.data?.status === "error") {
                        setError(resp.data?.message || "Server returned an error");
                        setDashData(null);
                    } else {
                        setDashData(resp.data?.data);
                    }
                } else {
                    console.error("fetchKioskFromDashboard error:", dashRes.reason);
                    setError((prev) => prev ?? "Failed to fetch kiosk dashboard data.");
                }

                // handle kiosk status result
                if (kioskRes.status === "fulfilled") {
                    const resp = kioskRes.value;
                    if (resp?.data?.error !== "Something went wrong") {
                        setKioskData(resp.data);
                        setKioskRunning(Boolean(resp?.data));
                    } else {
                        setKioskData({
                            notesStacked: 0,
                            amountStacked: 0,
                        });
                    }
                } else {
                    console.error("fetchKiosk error:", kioskRes.reason);
                    // optionally set fallback kioskData here
                }
                if (kioskF53Res.status === "fulfilled") {
                    const resp = kioskF53Res.value;
                    if (resp?.data?.error !== "Something went wrong") {
                        setKioskF53Data(resp.data);
                        setKioskF53Running(Boolean(resp?.data));
                    } else {
                        setKioskF53Data({});
                    }
                } else {
                    console.error("fetchKiosk error:", kioskF53Res.reason);
                    // optionally set fallback kioskData here
                }
            } catch (err: any) {
                console.error("Unexpected error in concurrent fetch:", err);
                setError(err?.message || "Unexpected error while fetching data.");
            } finally {
                if (isMounted) setIsLoading(false);
            }
        })();

        return () => {
            isMounted = false;
        };
    }, [kioskId, router]);
    return (
        <PageContainer title={`Kiosk ${kioskId ?? ""}`} description="Kiosk details">
            <Box >
                <Grid container spacing={3}>
                    {/* column */}
                    <Grid
                        size={{
                            xs: 12,
                            lg: 12
                        }}>

                        <TopCardsNew
                            receiverStatus={
                                isLoading ? (
                                    '...'
                                ) : kioskRunning ? (
                                    <Alert variant="filled" severity="success" className="text-white">
                                        Active
                                    </Alert>
                                ) : (
                                    <Alert variant="filled" severity="error">
                                        Inactive
                                    </Alert>
                                )
                            }
                            dispenserStatus={
                                isLoading ? (
                                    '...'
                                ) : kioskF53Running ? (
                                    <Alert variant="filled" severity="success" className="text-white">
                                        Active
                                    </Alert>
                                ) : (
                                    <Alert variant="filled" severity="error">
                                        Inactive
                                    </Alert>
                                )
                            }
                            kioskBalance={
                                isLoading
                                    ? "..."
                                    : `$${dashData && dashData?.nv200_balance
                                        ? parseInt(dashData?.nv200_balance) / 100
                                        : 0}`
                            }

                            kioskBillCount={
                                isLoading
                                    ? "..."
                                    : dashData && dashData?.bill_count
                                        ? dashData?.bill_count
                                        : 0
                            }
                        // kioskTotalDeposits={
                        //     isLoading ? '...' : `$${dashData && dashData?.totalDeposit}`
                        // }
                        />
                    </Grid>

                </Grid>
                <br />
                <Grid container spacing={2}>
                    <Grid
                        size={{
                            xs: 12,
                            lg: 12
                        }}>
                        <TopCardsNew2

                            todaysDeposits={
                                isLoading
                                    ? "..."
                                    : `$${parseInt(todaysDeposits?.total_denomination ?? 0)}`
                            }
                            todaysCashouts={
                                isLoading ? "..."
                                    : `$${parseInt(todaysCashouts?.total_amount ?? 0)}`
                            }
                        />
                    </Grid>
                </Grid>
                <br />
                <Grid container spacing={3}>

                    <ApexArea
                        graphData={todaysDepositsGraph}
                        startDate={startDate}
                        endDate={endDate}
                        setStartDate={setStartDate}
                        setEndDate={setEndDate}
                        onUpdate={() => fetchDailyDeposits(startDate, endDate)}
                        isLoading={isLoading}
                    />
                    <ApexArea2
                        graphData={todaysCashOutGraph}
                        startDate={startDate2}
                        endDate={endDate2}
                        setStartDate={setStartDate2}
                        setEndDate={setEndDate2}
                        onUpdate={() => fetchDailyCashouts(startDate2, endDate2)}
                        isLoading={isLoading}
                    />

                </Grid>
            </Box>
        </PageContainer>
    );
}
