"use client";
import React from "react";
import { useEffect, useState } from "react";

import { Grid, Box, Alert, Typography, Card, CardContent, IconButton, Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField } from "@mui/material";
import PageContainer from "@/app/components/container/PageContainer";
// components
import YearlyBreakup from "@/app/components/dashboards/modern/YearlyBreakup";
import MonthlyEarnings from "@/app/components/dashboards/modern/MonthlyEarnings";
import TopCards from "@/app/components/dashboards/modern/TopCards";
import RevenueUpdates from "@/app/components/dashboards/modern/RevenueUpdates";
import EmployeeSalary from "@/app/components/dashboards/modern/EmployeeSalary";
import Customers from "@/app/components/dashboards/modern/Customers";
import Projects from "@/app/components/dashboards/modern/Projects";
import Social from "@/app/components/dashboards/modern/Social";
import SellingProducts from "@/app/components/dashboards/modern/SellingProducts";
import WeeklyStats from "@/app/components/dashboards/modern/WeeklyStats";
import TopPerformers from "@/app/components/dashboards/modern/TopPerformers";
import axios from "axios";
import { useRouter } from "next/navigation";
import { getSession } from '@/utils/sessionData';
import TopCardsNew from "../components/dashboards/modern/TopCardsNew";
import Image from 'next/image';
import EditIcon from "@mui/icons-material/Edit";
export default function Dashboard() {
    const [isLoading, setIsLoading] = useState(true);
    useEffect(() => {
        setIsLoading(false);
    }, []);

    const router = useRouter();
    const checkSession = async () => {
        const session = getSession()
        if (!session?.admin_id && !session?.token) {
            router.push('/login')
        }
    }
    useEffect(() => {
        checkSession()
    }, [])
    // const { isLoading } = useGetAnalyticsDashboardWidgetsQuery();

    const [sessionData, setSessionData] = useState<any>();
    // const [isLoading, setIsLoading] = useState(false);
    const [kioskRunning, setKioskRunning] = useState<any>(false);
    const [kiosks, setKiosks] = useState<any[]>([]);
    const [selectedKiosk, setSelectedKiosk] = useState<any>(null);

    const [dashData, setDashData] = useState<any>({
        totalDeposit: 0,
        billCount: 0,
        balance: 0
    })
    const [kioskData, setKioskData] = useState<any>({
        amountStacked: 0,
        notesStacked: 0
    });

    const fetchData = async () => {
        try {
            setIsLoading(true);
            const token = sessionData?.token;

            const response = await axios.post(`/api/getDashboardData`, { token });
            if (response?.data?.status !== 'error') {

                setDashData(response?.data?.data);
            }
        } catch (error: any) {
            console.error(error.message);
        } finally {
            setIsLoading(false);
        }
    };

    const fetchKiosks = async () => {
        try {
            setIsLoading(true);
            const token = sessionData?.token;

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

            if (response?.data?.status !== 'error') {
                // assume response.data.kiosks is an array
                setKiosks(response?.data?.kiosks || []);
            } else {
                console.log(response?.data)
                setKiosks([])
            }
        } catch (error: any) {
            console.error(error.message);
        } finally {
            setIsLoading(false);
        }
    };

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

    useEffect(() => {
        if (sessionData?.token && sessionData?.admin_id) {
            fetchData();
            fetchKiosks();
        }
    }, [sessionData?.token, sessionData?.admin_id]);

    const handleKioskClick = (kiosk: any) => {
        const kioskId = kiosk.id ?? kiosk.kiosk_id ?? kiosk.kioskId;
        if (!kioskId) return;
        // navigate to kiosk details page and include kioskId in query params
        sessionStorage.setItem('kioskName', kiosk.kiosk_name)
        router.push(`/kiosk?kioskId=${encodeURIComponent(kioskId)}`);
    };
    const [editOpen, setEditOpen] = useState(false);
    const [editingKiosk, setEditingKiosk] = useState(null); // the whole kiosk object
    const [newKioskName, setNewKioskName] = useState("");
    const [oldKioskName, setOldKioskName] = useState("");

    const openEditDialog = (kiosk) => {
        setEditingKiosk(kiosk);
        setOldKioskName(
            (kiosk.kiosk_alias && kiosk.kiosk_alias.trim() !== "" ? kiosk.kiosk_alias : null) ??
            kiosk.kiosk_name ??
            kiosk.name ??
            `Kiosk ${kiosk.id ?? kiosk.kioskId ?? ""}`
        );
        // prefill with the chosen display name (alias preferred)
        setNewKioskName(
            (kiosk.kiosk_alias && kiosk.kiosk_alias.trim() !== "" ? kiosk.kiosk_alias : null) ??
            kiosk.kiosk_name ??
            kiosk.name ??
            `Kiosk ${kiosk.id ?? kiosk.kioskId ?? ""}`
        );
        setEditOpen(true);
    };

    const closeEditDialog = () => {
        setEditOpen(false);
        setEditingKiosk(null);
        setNewKioskName("");
    };

    // Replace this with your actual API call / update logic.
    // This example assumes you have a `kiosks` state and setKiosks to update the list locally.
    const renameKiosk = async (kioskId, kioskName, updatedName) => {
        try {
            // Example API request — replace URL and payload as needed:
            const res = await axios.post(`${process.env.NEXT_PUBLIC_API_BASE_URL}/kiosk/renameKiosk`,
                { kiosk_name: kioskName, new_name: updatedName },
                {
                    headers: { "Content-Type": "application/json" },

                });
            if (res?.data?.status !== 'error') {

                // If you have local kiosks state:
                setKiosks(prev => prev.map(k => k.kioskId === kioskId ? { ...k, kiosk_alias: updatedName } : k));

                // For demo, just simulate a small delay:
                await new Promise((r) => setTimeout(r, 300));
                fetchKiosks()
                fetchData()
                // After success:
                closeEditDialog();
            }
        } catch (err) {
            console.error("Rename failed:", err);
            // Optionally show user error toast/snackbar
        }
    };
    return (
        <PageContainer title="Dashboard" description="this is Dashboard">
            <Box>
                <Grid container spacing={3}>


                    {/* Kiosks grid */}
                    <Grid item xs={12}>
                        <Typography variant="h6" gutterBottom>
                            Kiosks
                        </Typography>

                        <Grid container spacing={2}>
                            {isLoading && kiosks.length === 0 ? (
                                <Typography>Loading kiosks…</Typography>
                            ) : kiosks.length === 0 ? (
                                <Typography>No kiosks found.</Typography>
                            ) : (
                                kiosks.map((kiosk: any, idx: number) => {
                                    // fallbacks in case fields differ
                                    const kioskId = kiosk.id ?? kiosk.kiosk_id ?? kiosk.kioskId ?? idx;
                                    const kioskName =
                                        (kiosk.kiosk_alias && kiosk.kiosk_alias.trim() !== '' ? kiosk.kiosk_alias : null) ??
                                        kiosk.kiosk_name ??
                                        kiosk.name ??
                                        `Kiosk ${kioskId}`;
                                    const kioskMetaValue = kiosk.value ?? kiosk.balance ?? kiosk.meta ?? 0;
                                    const kioskBillCount = kiosk.count ?? kiosk.billCount ?? kiosk.bills ?? 0;

                                    const isSelected = selectedKiosk && (selectedKiosk.id ?? selectedKiosk.kiosk_id) === kioskId;

                                    return (
                                        // <Grid
                                        //     key={kioskId}
                                        //     item
                                        //     xs={12}
                                        //     sm={6}
                                        //     md={4}
                                        //     lg={2}
                                        // >
                                        //     <br />
                                        //     <Card
                                        //         onClick={() => handleKioskClick(kiosk)}
                                        //         role="button"
                                        //         tabIndex={0}
                                        //         onKeyDown={(e) => {
                                        //             if (e.key === 'Enter' || e.key === ' ') handleKioskClick(kiosk);
                                        //         }}
                                        //         sx={{
                                        //             cursor: "pointer",
                                        //             margin: 0,
                                        //             padding: 0,

                                        //             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}>
                                        //                 {kioskName}
                                        //             </Typography>



                                        //             {isSelected && (
                                        //                 <Box mt={1}>
                                        //                     <Alert severity="info">Selected</Alert>
                                        //                 </Box>
                                        //             )}
                                        //         </CardContent>
                                        //     </Card>
                                        // </Grid>
                                        <Grid key={kioskId} item xs={12} sm={6} md={4} lg={2}>
                                            <br />
                                            <Card
                                                onClick={() => handleKioskClick(kiosk)}
                                                role="button"
                                                tabIndex={0}
                                                onKeyDown={(e) => {
                                                    if (e.key === "Enter" || e.key === " ") handleKioskClick(kiosk);
                                                }}
                                                sx={{
                                                    cursor: "pointer",
                                                    margin: 0,
                                                    padding: 0,
                                                    transition: "transform 120ms ease",
                                                    "&:hover": { transform: "translateY(-4px)" },
                                                    position: "relative" // important so the edit button can be positioned top-right
                                                }}
                                            >
                                                {/* EDIT BUTTON - top-right */}
                                                <IconButton
                                                    aria-label="Edit kiosk name"
                                                    onClick={(e) => {
                                                        e.stopPropagation(); // prevent card click
                                                        openEditDialog(kiosk);
                                                    }}
                                                    size="small"
                                                    sx={{
                                                        position: "absolute",
                                                        right: 6,
                                                        top: 6,
                                                        zIndex: 2,
                                                        bgcolor: "rgba(255,255,255,0.85)",
                                                        "&:hover": { bgcolor: "rgba(255,255,255,0.95)" }
                                                    }}
                                                >
                                                    <EditIcon fontSize="small" />
                                                </IconButton>

                                                <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}>
                                                        {kioskName}
                                                    </Typography>

                                                    {isSelected && (
                                                        <Box mt={1}>
                                                            <Alert severity="info">Selected</Alert>
                                                        </Box>
                                                    )}
                                                </CardContent>
                                            </Card>
                                        </Grid>
                                    );
                                })
                            )}
                        </Grid>
                    </Grid>

                    {/* Selected kiosk details area */}
                    {/* <Grid item xs={12}>
            <Box mt={2}>
              <Typography variant="subtitle1">Selected kiosk</Typography>
              {selectedKiosk ? (
                <Box component="pre" sx={{ bgcolor: 'background.paper', p: 2, borderRadius: 1, overflow: 'auto' }}>
                  {JSON.stringify(selectedKiosk, null, 2)}
                </Box>
              ) : (
                <Typography color="text.secondary">No kiosk selected. Click a kiosk above to select it.</Typography>
              )}
            </Box>
          </Grid> */}

                </Grid>
            </Box>
            <Dialog open={editOpen} onClose={closeEditDialog} fullWidth maxWidth="sm">
                <DialogTitle>Rename kiosk</DialogTitle>
                <DialogContent>
                    <TextField
                        autoFocus
                        margin="dense"
                        label="Kiosk name (alias)"
                        fullWidth
                        value={newKioskName}
                        onChange={(e) => setNewKioskName(e.target.value)}
                        onKeyDown={(e) => {
                            if (e.key === "Enter") {
                                // submit on enter
                                editingKiosk && renameKiosk(editingKiosk.kioskId ?? editingKiosk.id, oldKioskName, newKioskName);
                            }
                        }}
                    />
                </DialogContent>
                <DialogActions>
                    <Button onClick={closeEditDialog}>Cancel</Button>
                    <Button
                        variant="contained"
                        onClick={() => editingKiosk && renameKiosk(editingKiosk.kioskId ?? editingKiosk.id, oldKioskName, newKioskName)}
                        disabled={!newKioskName || newKioskName.trim() === ""}
                    >
                        Save
                    </Button>
                </DialogActions>
            </Dialog>
        </PageContainer>
    );
}
