"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, Button, Dialog, DialogActions, DialogContent, DialogTitle, Snackbar } from "@mui/material";
import Image from "next/image";
import TopCardsNew from "../components/dashboards/modern/TopCardsNew";
import CustomTextField from "../components/forms/theme-elements/CustomTextField";
import { IconRefresh } from "@tabler/icons-react";

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 [isSaving, setIsSaving] = useState<boolean>(false);
    const [snackbar, setSnackbar] = useState<SnackbarState>({ open: false, severity: 'success', message: '' });
    const [error, setError] = useState<string | null>(null);
    const [noteCount, setNoteCount] = useState<any>()
    const [sessionData, setSessionData] = useState<any>();
    // const [isLoading, setIsLoading] = useState(false);
    const [kioskRunning, setKioskRunning] = useState<any>(false);
    // 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
    })

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

    //     const session = getSessionData();
    //     if (!session?.token) {
    //         // not logged in — redirect to login
    //         router.push("/login");
    //         return;
    //     }

    //     const fetchKioskFromDashboard = async () => {
    //         try {
    //             setIsLoading(true);
    //             setError(null);
    //             const token = session.token;
    //             // NOTE: call getDashboardData and pass kioskId so the API returns kiosk-specific dashboard payload
    //             // Adjust the request body/params to match what your backend expects.
    //             const response = await axios.post(`/api/getDashboardData`, { token, kioskId });

    //             // Expected: response.data.data contains kiosk-specific fields (like cassettes, amountStacked, etc.)
    //             if (response?.data?.status === 'error') {
    //                 setError(response?.data?.message || 'Server returned an error');
    //                 setDashData(null);
    //             } else {
    //                 // If your API wraps data differently, adjust this line
    //                 setDashData(response?.data?.data ?? response?.data);
    //             }
    //         } catch (err: any) {
    //             console.error(err);
    //             setError(err?.message || "Failed to fetch kiosk data.");
    //         } finally {
    //             setIsLoading(false);
    //         }
    //     };
    //     const fetchKiosk = async () => {
    //         try {
    //             setIsLoading(true);
    //             const token = sessionData?.token;
    //             const kioskName = sessionStorage?.get('kioskName') ?? ''

    //             const response = await axios.post(`/api/getKioskStatus`, { token, kioskName });
    //             console.log(response)

    //             if (response?.data?.error !== 'Something went wrong') {
    //                 console.log(response?.data)
    //                 setKioskData(response?.data)
    //                 setKioskRunning(response?.data?.running)
    //                 // setDashData(response?.data?.data);
    //             } else {
    //                 console.log(response?.data)
    //                 setKioskData({
    //                     notesStacked: 0,
    //                     amountStacked: 0
    //                 })
    //             }
    //         } catch (error: any) {
    //             console.error(error.message);
    //         } finally {
    //             setIsLoading(false);
    //         }
    //     };
    //     fetchKioskFromDashboard();
    //     fetchKiosk();
    // }, [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/getKioskNotes`, { token, kioskName });

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

                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 ?? resp.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?.running));
                    } else {
                        setKioskData({
                            notesStacked: 0,
                            amountStacked: 0,
                        });
                    }
                } else {
                    console.error("fetchKiosk error:", kioskRes.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]);
    const fetchKioskData = async () => {
        setIsLoading(true);
        setError(null);
        const session = getSessionData();
        if (!session?.token) {
            router.push("/login");
            return;
        }
        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/getKioskNotes`, { token, kioskName });

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



            // 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 ?? resp.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?.running));
                } else {
                    setKioskData({
                        notesStacked: 0,
                        amountStacked: 0,
                    });
                }
            } else {
                console.error("fetchKiosk error:", kioskRes.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 {
            setIsLoading(false);
        }
    }

    interface CassettePayload {
        cassett_id: number;
        value: number;
        count: number;
    }

    interface CassetteState {
        id?: number;
        cassett_id: number;
        value: string;
        count: string;
        denomination: any;
        note_count: any;
    }

    type SnackbarState = {
        open: boolean;
        severity: 'success' | 'error' | 'warning' | 'info';
        message: string;
    };
    const [open, setOpen] = React.useState(false);
    const [openReset, setOpenReset] = React.useState(false);

    const [selectedCassette, setSelectedCassette] = useState<CassetteState | null>(null);
    const [selectedCassetteIdx, setSelectedCassetteIdx] = useState<number | null>(null);
    const handleClickOpen = (c: CassetteState, idx: number) => {
        console.log(c)
        // open dialog with a deep copy so we don't mutate array until save
        setSelectedCassette({ ...c });
        setSelectedCassetteIdx(idx);
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
        setSelectedCassette(null);
        setSelectedCassetteIdx(null);
    };
    const handleCloseReset = () => {
        setOpenReset(false);

    };
    const saveOne = async (kiosk: any) => {
        const kioskName = sessionStorage?.getItem('kioskName') ?? ''
        try {
            setIsSaving(true)
            const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}/kiosk/setKioskNotes`;
            const payload = {
                kioskName: kioskName,
                denomination: kiosk?.denomination,
                note_count: noteCount
            }
            const response = await axios.post(url, payload, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            console.log(response)
            if (response?.data?.status !== 'error') {
                setIsSaving(false)
                handleClose()
                fetchKioskData()
            }
        } catch (err) {
            // eslint-disable-next-line no-console
            console.error(err);

        } finally {
            setIsSaving(false);
        }
    };
    const resetNV200 = async () => {
        const kioskName = sessionStorage?.getItem('kioskName') ?? ''
        try {
            setIsSaving(true)
            const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}/kiosk/resetKioskNotes`;
            const payload = {
                kioskName: kioskName,
             
            }
            const response = await axios.post(url, payload, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            console.log(response)
            if (response?.data?.status !== 'error') {
                setIsSaving(false)
                handleCloseReset()
                fetchKioskData()
            }
        } catch (err) {
            // eslint-disable-next-line no-console
            console.error(err);

        } finally {
            setIsSaving(false);
        }
    }
    return (
        <PageContainer title={`Kiosk ${kioskId ?? ""}`} description="Kiosk details">
            <Box >
                <Grid container spacing={3}>
                    <Grid>
                        <Typography variant="h6" gutterBottom>
                            Kiosk {isLoading ? '- Loading...' : `- ${kioskData?.kioskNotes?.[0]?.kiosk_name ?? ''}`}
                        </Typography>
                        <Button
                            sx={{ marginTop: 2 }}
                            onClick={() => { setOpenReset(true) }}
                        >
                            <IconRefresh /> &nbsp;
                            Reset NV200
                        </Button>

                        <Grid container spacing={2}>
                            {isLoading && kioskData?.kioskNotes?.length === 0 ? (
                                <Typography>Loading kiosk notes…</Typography>
                            ) : kioskData?.kioskNotes?.length === 0 ? (
                                <Typography>No notes found.</Typography>
                            ) : (
                                kioskData?.kioskNotes?.map((kiosk: any, idx: number) => {
                                    // fallbacks in case fields differ
                                    const kioskId = kiosk?.id ?? idx;
                                    const kioskDenom = kiosk?.denomination ?? '';
                                    const kioskNoteCount = kiosk?.note_count ?? '';

                                    return (
                                        <Grid
                                            key={kioskId}
                                        >
                                            <br />
                                            <Card
                                                onClick={() => {
                                                    handleClickOpen(kiosk, idx)
                                                    setNoteCount(kiosk?.note_count)
                                                }}

                                                role="button"
                                                tabIndex={0}

                                                sx={{
                                                    cursor: "pointer",
                                                    margin: 0,
                                                    padding: 0,
                                                    //   border: isSelected ? "2px solid" : "1px solid",
                                                    //   borderColor: isSelected ? "primary.main" : "divider",
                                                    transition: "transform 120ms ease",
                                                    "&:hover": { transform: "translateY(-4px)" }
                                                }}
                                            >
                                                <CardContent sx={{ textAlign: "center", bgcolor: "primary.light" }}>
                                                    <Box sx={{ display: "flex", justifyContent: "center", mb: 1 }}>
                                                        <Image src="/images/svgs/icon-briefcase.svg" alt="kiosk" width={50} height={50} />
                                                    </Box>

                                                    <Typography mt={1} variant="subtitle1" fontWeight={600}>
                                                        Denomination - ${kioskDenom}
                                                    </Typography>

                                                    <Typography mt={1} variant="subtitle1" fontWeight={600}>
                                                        Bill Count - {kioskNoteCount}
                                                    </Typography>


                                                </CardContent>
                                            </Card>
                                        </Grid>
                                    );
                                })
                            )}
                        </Grid>
                    </Grid>
                </Grid>

            </Box>
            <Dialog open={open} onClose={handleClose}>
                <DialogTitle>Denomination - ${selectedCassette?.denomination}</DialogTitle>
                <DialogContent>
                    <Box sx={{ mt: 2 }}>
                        <CustomTextField
                            autoFocus
                            margin="dense"
                            id="value"
                            label="Denomination ($)"
                            type="text"
                            value={parseInt(selectedCassette?.denomination) ?? ''}
                            onChange={(e: any) => parseInt(selectedCassette?.denomination) ?? ''}

                            // onChange={(e: any) => handleDialogFieldChange('value', e.target.value)}
                            fullWidth
                        />
                    </Box>
                    <Box sx={{ mt: 2 }}>
                        <CustomTextField
                            margin="dense"
                            id="count"
                            label="Count"
                            type="text"
                            value={noteCount}
                            onChange={(e: any) => setNoteCount(e.target.value)}
                            fullWidth
                        />
                    </Box>
                </DialogContent>
                <DialogActions>
                    <Button color="error" onClick={handleClose} disabled={isSaving}>Cancel</Button>
                    <Button onClick={() => saveOne(selectedCassette)} disabled={isSaving}>
                        {isSaving ? 'Saving...' : 'Update'}
                    </Button>
                </DialogActions>
            </Dialog>
            <Dialog open={openReset} onClose={handleCloseReset}>
                <DialogTitle>Are you sure you want to reset NV200?</DialogTitle>
                <br />
                <DialogActions>
                    <Button color="error" onClick={handleCloseReset} disabled={isSaving}>Cancel</Button>
                    <Button onClick={() => resetNV200()} disabled={isSaving}>
                        {isSaving ? 'Resetting...' : 'Reset'}
                    </Button>
                </DialogActions>
            </Dialog>
            <Snackbar open={snackbar.open} autoHideDuration={3000} onClose={() => setSnackbar(s => ({ ...s, open: false }))}>
                <Alert severity={snackbar.severity} onClose={() => setSnackbar(s => ({ ...s, open: false }))}>
                    {snackbar.message}
                </Alert>
            </Snackbar>
        </PageContainer >
    );
}
