"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";

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>([]);
    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);

    // 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();
        }
    }, [sessionData?.token, sessionData?.admin_id]);

    // -------------------------
    // UPDATE BALANCE HANDLER
    // -------------------------
    const openUpdateBalanceModal = (id: number, currentBalance: string) => {
        setSelectedAdminId(id);
        setBalanceValue(currentBalance);
        setOpenBalanceModal(true);
    };

    const handleUpdateBalance = async () => {
        if (!balanceValue || !selectedAdminId) return;

        try {
            setIsLoading(true);
            const response = await axios.post("/api/updateAdminBalance", {
                token: sessionData?.token,
                id: selectedAdminId,
                balance: balanceValue
            });

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

            setSuccess("Balance updated successfully!");
            setOpenBalanceModal(false);

            // Refresh admins list
            getAdmins();
        } catch (err: any) {
            setError(err.message || "Failed to update balance");
        } finally {
            setIsLoading(false);
        }
    };
    const handleAddBalance = async () => {
        if (!balanceValue || !selectedAdminId) return;

        try {
            setIsLoading(true);
            const response = await axios.post("/api/addAdminBalance", {
                token: sessionData?.token,
                id: selectedAdminId,
                amount: balanceValue
            });

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

            setSuccess("Balance updated successfully!");
            setOpenBalanceModal(false);

            // Refresh admins list
            getAdmins();
        } catch (err: any) {
            setError(err.message || "Failed to update balance");
        } finally {
            setIsLoading(false);
        }
    };
    const handleRemoveBalance = async () => {
        if (!balanceValue || !selectedAdminId) return;

        try {
            setIsLoading(true);
            const response = await axios.post("/api/removeAdminBalance", {
                token: sessionData?.token,
                id: selectedAdminId,
                amount: balanceValue
            });

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

            setSuccess("Balance updated successfully!");
            setOpenBalanceModal(false);

            // Refresh admins list
            getAdmins();
        } catch (err: any) {
            setError(err.message || "Failed to update balance");
        } finally {
            setIsLoading(false);
        }
    };
    // -------------------------
    // DELETE HANDLER
    // -------------------------
    const openDeleteConfirmModal = (id: number) => {
        setDeleteAdminId(id);
        setOpenDeleteModal(true);
    };

    const handleDeleteAdmin = async () => {
        if (!deleteAdminId) return;

        try {
            setIsLoading(true);
            const response = await axios.post("/api/deleteAdmin", {
                token: sessionData?.token,
                id: deleteAdminId
            });

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

            setSuccess("Employee deleted successfully!");
            setOpenDeleteModal(false);

            // Refresh admins list
            getAdmins();
        } catch (err: any) {
            setError(err.message || "Failed to delete employee");
        } finally {
            setIsLoading(false);
        }
    };
    const handleAddEmployee = async () => {
        const { first, last, email, phone, username } = newEmployee;
        if (!first || !last || !email || !phone || !username) {
            setError("All fields are required");
            return;
        }

        try {
            setIsLoading(true);

            const response = await axios.post("/api/addEmployee", {
                token: sessionData?.token,
                first,
                last,
                email,
                phone,
                username
            });

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

            setSuccess("Employee added successfully!");
            setOpenAddModal(false);

            // Clear form
            setNewEmployee({
                first: "",
                last: "",
                email: "",
                phone: "",
                username: ""
            });

            // Refresh grid
            getAdmins();
        } catch (err: any) {
            setError(err.message || "Unable to add employee");
        } finally {
            setIsLoading(false);
        }
    };
    // -------------------------
    // COLUMNS
    // -------------------------
    const columns = [
        {
            field: "username",
            headerName: "Username",
            flex: 1,
            minWidth: 150,
            renderCell: (params: GridRenderCellParams) => (
                <span style={{ fontWeight: 600 }}>{params.value}</span>
            )
        },
        
        {
            field: "id",
            headerName: "View",
            flex: 1,
            minWidth: 150,
            renderCell: (params: GridRenderCellParams) => (
                <Button
                    variant="contained"
                    onClick={() => router.push(`/viewSchedules/${params.row.id}`)}
                >
                    View
                </Button>
            )
        },
       
    ];
    useEffect(() => {
        if (user && user.role !== "Super") {
            router.push("/dashboard");
        }
    }, [user]);
    return (
        <PageContainer title={"Schedules - 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%" } }}>
                    <BaseCard title="Schedules">
                        {/* <Box sx={{ width: "100%", display: "flex", justifyContent: "flex-end", mb: 2 }}>
                            <Button
                                variant="contained"
                                color="primary"
                                onClick={() => setOpenAddModal(true)}
                            >
                                Add Employee
                            </Button>
                        </Box> */}
                        {isLoading && (
                            <>
                                <LinearProgress />
                                <br />
                            </>
                        )}

                        <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"
                                        }
                                    }}
                                />
                            )}
                        </Box>
                    </BaseCard>
                </Grid>
            </Grid>

            {/* -----------------------------------
           UPDATE BALANCE MODAL
      ----------------------------------- */}
            <Dialog
                open={openBalanceModal}
                onClose={() => setOpenBalanceModal(false)}
                fullWidth
                maxWidth="xs">
                <DialogTitle>Update Balance</DialogTitle>
                <DialogContent sx={{ mt: 1 }}>
                    <br />
                    <TextField
                        fullWidth
                        label="Balance Amount"
                        type="number"
                        value={balanceValue}
                        onChange={(e) => setBalanceValue(e.target.value)}
                    />
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setOpenBalanceModal(false)}>Cancel</Button>
                    <Button variant="contained" color="error" onClick={handleRemoveBalance}>
                        Remove
                    </Button>
                    <Button variant="contained" color="success" onClick={handleAddBalance}>
                        Add
                    </Button>
                </DialogActions>
            </Dialog>

            {/* -----------------------------------
           DELETE CONFIRMATION MODAL
      ----------------------------------- */}
            <Dialog open={openDeleteModal} onClose={() => setOpenDeleteModal(false)} >
                <DialogTitle>Delete Employee</DialogTitle>
                <DialogContent>
                    <Typography sx={{ mt: 1 }}>
                        Are you sure you want to delete this employee?
                    </Typography>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setOpenDeleteModal(false)}>Cancel</Button>
                    <Button variant="contained" color="error" onClick={handleDeleteAdmin}>
                        Yes, Delete
                    </Button>
                </DialogActions>
            </Dialog>
            <Dialog
                open={openAddModal}
                onClose={() => setOpenAddModal(false)}
                fullWidth
                maxWidth="xs"
            >
                <DialogTitle>Add Employee</DialogTitle>

                <DialogContent sx={{ mt: 1 }}>
                    <br />
                    <TextField
                        fullWidth
                        label="First Name"
                        value={newEmployee.first}
                        sx={{ mb: 2 }}
                        onChange={(e) =>
                            setNewEmployee({ ...newEmployee, first: e.target.value })
                        }
                    />
                    <TextField
                        fullWidth
                        label="Last Name"
                        value={newEmployee.last}
                        sx={{ mb: 2 }}
                        onChange={(e) =>
                            setNewEmployee({ ...newEmployee, last: e.target.value })
                        }
                    />
                    <TextField
                        fullWidth
                        label="Username"
                        value={newEmployee.username}
                        sx={{ mb: 2 }}
                        onChange={(e) =>
                            setNewEmployee({ ...newEmployee, username: e.target.value })
                        }
                    />
                    <TextField
                        fullWidth
                        label="Email"
                        value={newEmployee.email}
                        sx={{ mb: 2 }}
                        onChange={(e) =>
                            setNewEmployee({ ...newEmployee, email: e.target.value })
                        }
                    />
                    <TextField
                        fullWidth
                        label="Phone No (*Add country code with out + i.e.: 1,91)"
                        value={newEmployee.phone}
                        sx={{ mb: 2 }}
                        onChange={(e) =>
                            setNewEmployee({ ...newEmployee, phone: e.target.value })
                        }
                    />
                </DialogContent>

                <DialogActions>
                    <Button onClick={() => setOpenAddModal(false)}>Cancel</Button>
                    <Button variant="contained" onClick={handleAddEmployee}>
                        Save
                    </Button>
                </DialogActions>
            </Dialog>
        </PageContainer>
    );
}
