"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, Switch } from "@mui/material";
import BaseCard from "../components/shared/BaseCard";
import { getSession } from '@/utils/sessionData';
import { DataGrid, GridRenderCellParams } 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 [admins, setAdmins] = useState<any>([]);

    // --- Helper to clear alerts after a few seconds ---
    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)
                setIsLoading(false);
            } else {
                setError(response?.data?.message)
                setIsLoading(false);
            }
        } 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)
                setIsLoading(false);
            } else {
                setError(response?.data?.message)
                setIsLoading(false);
            }
        } catch (error: any) {
            setError(error?.message ?? 'Unable to fetch admin')
            setIsLoading(false);
        }
    }

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

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

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


    // --- UPDATE 1: Accept targetUsername as a parameter ---
    const handleStatusChange = async (id: any, currentValue: string, targetUsername: string) => {
        const newValue = currentValue == '1' ? '0' : '1';

        const previousAdmins = [...admins];
        const updatedAdmins = admins.map((admin: any) =>
            admin.id === id ? { ...admin, mobile_login: newValue } : admin
        );
        setAdmins(updatedAdmins);

        try {
            const response = await axios.post('/api/updateMobileLogin', {
                token: sessionData?.token,
                id: id,
                username: targetUsername, // --- UPDATE 2: Use the passed username, not session username ---
                status: newValue
            });

            if (response?.data?.status === 'error') {
                throw new Error(response?.data?.message);
            }

            setSuccess(`Status updated for user: ${targetUsername}`);

        } catch (err: any) {
            // Revert change if API fails
            setAdmins(previousAdmins);
            setError(err?.message || 'Failed to update status');
            console.error(err);
        }
    };

    const columns = [
        {
            field: "username",
            headerName: "Username",
            flex: 1,
            minWidth: 150,
            renderCell: (params: GridRenderCellParams) => (
                <span style={{ fontWeight: 600 }}>{params.value}</span>
            ),
        },
        {
            field: "mobile_login",
            headerName: "Enable / Disable",
            flex: 1,
            minWidth: 120,
            renderCell: (params: GridRenderCellParams) => (
                <Switch
                    checked={params.value == '1'}
                    color='success'
                    // --- UPDATE 3: Pass params.row.username to the handler ---
                    onChange={() => handleStatusChange(
                        params.row.id,
                        params.value as string,
                        params.row.username
                    )}
                />
            ),
        },
    ];
    useEffect(() => {
        if (user && user.role !== "Super") {
            router.push("/dashboard");
        }
    }, [user]);
    return (
        <PageContainer title={'Mobile Logins - Emanage'} description="Kiosk details">
            <Grid container spacing={2}>
                <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: '100%' } }}>
                    <BaseCard title="Employees">
                        <Box sx={{ width: "100%" }}>
                            {admins.length > 0 ? (
                                <DataGrid
                                    rows={admins}
                                    columns={columns}
                                    pageSizeOptions={[10, 20]}
                                    initialState={{
                                        pagination: { paginationModel: { pageSize: 10 } },
                                    }}
                                    sx={{
                                        border: "none",
                                        "& .MuiDataGrid-cell:focus": { outline: "none !important" },
                                        "& .MuiDataGrid-cell:focus-within": { outline: "none !important" },
                                        "& .MuiDataGrid-row:focus": { outline: "none !important" },
                                        "& .MuiDataGrid-row:focus-within": { outline: "none !important" },
                                        "& .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 }}>Loading...</Typography>
                            )}
                        </Box>
                    </BaseCard>
                </Grid>
            </Grid>
        </PageContainer >
    );
}