"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, Button, TextField, LinearProgress, Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material";
import BaseCard from "../components/shared/BaseCard";
import { getSession } from '../../utils/sessionData';
import Autocomplete from '@mui/material/Autocomplete';
import { styled } from '@mui/material/styles';
import dayjs, { Dayjs } from 'dayjs';
import { MobileDateTimePicker } from '@mui/x-date-pickers/MobileDateTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DataGrid } from "@mui/x-data-grid";
import moment from "moment-timezone";

// Styled component definition
// const CustomTextField = styled((props: any) => <TextField {...props} />)(({ theme }: any) => ({
//     '& .MuiOutlinedInput-input::-webkit-input-placeholder': {
//         color: theme.palette.text.secondary,
//         opacity: '0.8',
//     },
//     '& .MuiOutlinedInput-input.Mui-disabled::-webkit-input-placeholder': {
//         color: theme.palette.text.secondary,
//         opacity: '1',
//     },
//     '& .Mui-disabled .MuiOutlinedInput-notchedOutline': {
//         borderColor: theme.palette.grey[200],
//     },
// }));
const CustomTextField = styled(TextField, {
    shouldForwardProp: (prop) =>
        prop !== "sectionListRef" &&
        prop !== "areAllSectionsEmpty",
})(({ theme }) => ({
    '& .MuiOutlinedInput-input::placeholder': {
        color: theme.palette.text.secondary,
        opacity: 0.8,
    },
}));
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 [logins, setLogins] = useState<any>([]);
    const [rows, setRows] = useState<any>([])
    const [totalTime, setTotalTime] = useState<any>('');
    const [totalAmount, setTotalAmount] = useState<any>('')
    const [isIndian, setIsIndian] = useState<any>(false);
    const [timezones, setTimezones] = useState<any>(['MST', 'IST']);

    // --- Filter States ---
    const [selectedEmployee, setSelectedEmployee] = useState<any | null>(null);
    const [selectedTimezone, setSelectedTimezone] = useState<any | null>('IST');

    const [inputValue, setInputValue] = useState('');
    const [inputValue2, setInputValue2] = useState('');

    const [fromDate, setFromDate] = useState<Dayjs | null>(dayjs().startOf('day'));
    const [toDate, setToDate] = useState<Dayjs | null>(dayjs().endOf('day'));

    const [openEditModal, setOpenEditModal] = useState(false);
    const [openDeleteModal, setOpenDeleteModal] = useState(false);

    const [selectedRow, setSelectedRow] = useState<any>(null);
    const [editDateTime, setEditDateTime] = useState<any>(null);
    const [selectedRealId, setSelectedRealId] = useState<any>(null);

    // function formatWithMoment(datetime: any) {
    //     return moment(datetime, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD h:mm A");
    // }
    useEffect(() => {
        if (logins.length > 0) {
            setRows(
                logins.map((item: any, index: any) => ({
                    real_id: item.real_id,
                    id: index + 1,
                    logtime: item.logtime,
                    type: item.type,
                    created_at: item.created_at,
                }))
            );
        } else {
            setRows([]);
        }
    }, [logins]);


    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);
        }
    }

    const handleFetchData = async () => {
        setIsLoading(true)
        if (!selectedEmployee) {
            setError("Please select an employee");
            setIsLoading(false)

            return;
        }
        console.log("Fetching data for:", {
            admin: selectedEmployee.username,
            timezone: selectedTimezone,
            from: fromDate?.format('YYYY-MM-DD HH:mm:ss'),
            to: toDate?.format('YYYY-MM-DD HH:mm:ss')
        });
        try {
            const token = sessionData?.token ?? '';
            const payload = {
                token,
                admin: selectedEmployee?.username,
                timezone: selectedTimezone,
                from: fromDate?.format('YYYY-MM-DD HH:mm:ss'),
                to: toDate?.format('YYYY-MM-DD HH:mm:ss')
            }
            const response = await axios.post('/api/report', payload)
            if (response?.data?.status !== 'error') {
                console.log(response?.data?.data)
                setLogins(response?.data?.data)
                setSuccess(`Data fetched for: ${selectedEmployee?.username}`)
                setTotalTime(response?.data?.total_time)
                setTotalAmount(response?.data?.amount)
                setIsIndian(response?.data?.isIndianWageApplied)
                setIsLoading(false)

            } else {
                setError('Unable to fetch data')
                setIsLoading(false)

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

        } finally {
            setIsLoading(false)
        }
    };

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

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

    useEffect(() => {
        if (sessionData?.token) {
            getAdmin()
            getAdmins()
        }
    }, [sessionData?.token, sessionData?.admin_id])
    useEffect(() => {
        if (user && user.role !== "Super") {
            router.push("/dashboard");
        }
    }, [user]);

    const quickAddBalance = async () => {
        try {
            setIsLoading(true);
            const payload = {
                token: sessionData?.token ?? '',

                amount: totalAmount,
                id: selectedEmployee?.id
            }
            const response = await axios.post('/api/quickAddBalance', payload)
            if (response?.data?.status !== 'error') {
                setSuccess('Balance updated')
            } else {
                setError('Unable to update balance')
            }
        } catch (error: any) {
            setError(error?.message)
        } finally {
            setIsLoading(false)
        }
    }
    const handleExport = async () => {
        try {
            setIsLoading(true);

            const payload = {
                token: sessionData?.token ?? '',
                from: fromDate,
                to: toDate,
                admin: selectedEmployee?.username
            };

            const response = await axios.post("/api/exportReport", payload);

            if (response.data?.status !== "success") {
                setError("Failed to export report");
                return;
            }

            const pdfUrl = response.data.url;

            // Download automatically
            const link = document.createElement("a");
            link.href = pdfUrl;
            link.download = `WagesReport_${selectedEmployee?.username}.pdf`;
            link.click();

        } catch (error: any) {
            setError(error.message);
        } finally {
            setIsLoading(false);
        }
    };
    const handleUpdateTime = async () => {
        try {
            setIsLoading(true);

            const token = sessionData?.token ?? "";

            const tz = selectedTimezone == 'MST'
                ? 'America/Denver'
                : 'Asia/Kolkata';

            const newTime = moment
                .tz(editDateTime.format("YYYY-MM-DD HH:mm:ss"), tz)
                .utc()
                .format("YYYY-MM-DD HH:mm:ss");

            const res = await axios.post('/api/updateTime', {
                token,
                id: selectedRow.real_id,
                time: newTime
            });

            if (res.data.status !== "error") {
                setOpenEditModal(false);
                handleFetchData();
            } else {
                alert("Failed to update time");
            }

        } catch (err) {
            alert("Error updating log time");
        } finally {
            setIsLoading(false);
        }
    };
    // const handleUpdateTime = async () => {
    //     try {
    //         setIsLoading(true);
    //         const token = sessionData?.token ?? "";
    //         const newTime = editDateTime?.format("YYYY-MM-DD HH:mm:ss");
    //         console.log(selectedRow)
    //         const res = await axios.post('/api/updateTime', {
    //             token,
    //             id: selectedRow.real_id,
    //             time: newTime,
    //             type: selectedRow.type
    //         });

    //         if (res.data.status !== "error") {
    //             setOpenEditModal(false);
    //             // refresh table
    //             handleFetchData();
    //         } else {
    //             alert("Failed to update time");
    //         }
    //     } catch (err) {
    //         alert("Error updating log time");
    //     } finally {
    //         setIsLoading(false);
    //     }
    // };
    const handleDeleteTime = async () => {
        try {
            setIsLoading(true);

            const token = sessionData?.token ?? "";
            console.log(selectedRow)
            const res = await axios.post('/api/deleteTime', {
                token,
                id: selectedRow.real_id,

            });
            if (res.data.status !== "error") {
                setOpenDeleteModal(false);
                // refresh table
                handleFetchData();
            } else {
                alert("Failed to update time");
            }
        } catch (err) {
            alert("Error updating log time");
        } finally {
            setIsLoading(false);

        }
    }
    function formatWithMoment(time: any, timezone: any) {
        return moment
            .utc(time)
            .tz(timezone)
            .format("YYYY-MM-DD h:mm A");
    }
    const columns = [
        // {
        //     field: "id",
        //     headerName: "Real Id",
        //     flex: 1,
        //     renderCell: (params: any) => {
        //         console.log("params.id =", params.id, " | params.row.id =", params.real_id);
        //         { params.real_id; }
        //     }
        // },
        {
            field: "logtime",
            headerName: "Time",
            flex: 1,
            renderCell: (params: any) => {
                // console.log(params.row.created_at)
                const tz = selectedTimezone == 'MST' ? 'America/Denver' : 'Asia/Kolkata';
                return (
                    <span style={{ fontWeight: 700 }}>
                        {formatWithMoment(params.row.created_at, tz)}
                    </span>
                )
            }

        },
        {
            field: "type",
            headerName: "Type",
            flex: 1,
            renderCell: (params: any) => (
                <span style={{ color: params.value === 1 ? 'green' : 'red', fontWeight: 700 }}>
                    {params.value === 1 ? 'Login' : 'Logout'}
                </span>
            )
        },
        {
            field: "created_at",
            headerName: "Edit",
            flex: 1,
            renderCell: (params: any) => {
                const tz = selectedTimezone == 'MST' ? 'America/Denver' : 'Asia/Kolkata';
                return (
                    <Button
                        variant="contained"
                        color="primary"
                        onClick={() => {
                            setSelectedRow(params.row);
                            setSelectedRealId(params.row.real_id);
                            setEditDateTime(dayjs(formatWithMoment(params.row.created_at, tz))); // preload
                            setOpenEditModal(true);
                        }}
                    >
                        Edit
                    </Button>
                )
            }
        },
        {
            field: "updated_at",
            headerName: "Delete",
            flex: 1,
            renderCell: (params: any) => (
                <Button
                    variant="contained"
                    color="error"
                    onClick={() => {
                        setSelectedRow(params.row);
                        setSelectedRealId(params.row.real_id);
                        setOpenDeleteModal(true);
                    }}>
                    Delete
                </Button>
            )
        },
    ];
    return (
        <PageContainer title={'Employee Reports - Emanage'} description="Kiosk details">
            <Box sx={{ width: '100%' }}>
                {/* Error/Success Messages */}
                <Box sx={{ mb: 2 }}>
                    {error && <Alert severity="error" onClose={() => setError(null)}>{error}</Alert>}
                    {success && <Alert severity="success" onClose={() => setSuccess(null)}>{success}</Alert>}
                </Box>

                <BaseCard title="Employee Reports">
                    {isLoading && <><LinearProgress /><br /></>}

                    <Box sx={{ width: "100%" }}>
                        <LocalizationProvider dateAdapter={AdapterDayjs}>


                            <Box sx={{
                                display: 'grid',
                                gap: 2,

                                gridTemplateColumns: {
                                    xs: '1fr',
                                    md: '1fr 1fr',
                                    lg: 'repeat(5, 1fr)'
                                }
                            }}>


                                <Autocomplete
                                    id="admin-select-autocomplete"
                                    options={admins}
                                    getOptionLabel={(option: any) => option.username || ""}
                                    isOptionEqualToValue={(option: any, value: any) => option.id === value.id}
                                    value={selectedEmployee}
                                    onChange={(event: any, newValue: any) => {
                                        setSelectedEmployee(newValue);
                                    }}
                                    inputValue={inputValue}
                                    onInputChange={(event, newInputValue) => {
                                        setInputValue(newInputValue);
                                    }}
                                    loading={isLoading}
                                    fullWidth
                                    renderInput={(params) => (
                                        <CustomTextField
                                            {...params}
                                            placeholder="Select an Employee"
                                            label="Search Employee"
                                            size="small"
                                        />
                                    )}
                                />
                                <Autocomplete
                                    id="admin-select-autocomplete"
                                    options={timezones}
                                    getOptionLabel={(option: any) => option || ""}
                                    isOptionEqualToValue={(option: any, value: any) => option === value}
                                    value={selectedTimezone}
                                    onChange={(event: any, newValue: any) => {
                                        setSelectedTimezone(newValue);
                                    }}
                                    inputValue={inputValue2}
                                    onInputChange={(event, newInputValue) => {
                                        setInputValue2(newInputValue);
                                    }}
                                    loading={isLoading}
                                    fullWidth
                                    renderInput={(params) => (
                                        <CustomTextField
                                            {...params}
                                            placeholder="Select Timezone"
                                            label="Search Timezone"
                                            size="small"
                                        />
                                    )}
                                />
                                <MobileDateTimePicker
                                    label="From Date"
                                    value={fromDate}
                                    minutesStep={1}
                                    timeSteps={{ minutes: 1 }}

                                    onChange={(newValue) => setFromDate(newValue)}
                                    slotProps={{
                                        textField: {
                                            fullWidth: true,
                                            size: "small",
                                            variant: "outlined",
                                        },
                                    }}
                                />
                                <MobileDateTimePicker
                                    enableAccessibleFieldDOMStructure={false}
                                    label="To Date"
                                    value={toDate}
                                    minutesStep={1}
                                    timeSteps={{ minutes: 1 }}

                                    onChange={(newValue) => setToDate(newValue)}
                                    slots={{ textField: CustomTextField }}
                                    slotProps={{
                                        textField: {
                                            fullWidth: true,
                                            size: "small",
                                            variant: "outlined",
                                        },
                                    }}
                                />
                                <Button
                                    variant="contained"
                                    color="primary"
                                    fullWidth
                                    size="large"
                                    onClick={handleFetchData}
                                    sx={{ height: '40px' }}
                                >
                                    Fetch Data
                                </Button>

                            </Box>
                        </LocalizationProvider>
                    </Box>
                    {totalTime && (
                        <Grid
                            container
                            sx={{
                                width: "100%",
                                mt: 3,
                                alignItems: "center",
                                justifyContent: "space-between"
                            }}
                        >

                            {/* LEFT SECTION */}
                            <Grid sx={{ width: { xs: "100%", lg: "50%" } }}>
                                <Box>
                                    <Typography sx={{ fontSize: 22, fontWeight: "bold", ml: 1 }}>
                                        Total Hours: {`${totalTime.hours} Hours ${totalTime.minutes} Minutes`}
                                    </Typography>

                                    <Typography sx={{ fontSize: 22, fontWeight: "bold", ml: 1, mt: 1 }}>
                                        Amount: {isIndian ? '₹' : '$'}{totalAmount}
                                    </Typography>
                                </Box>
                            </Grid>

                            {/* RIGHT SECTION */}
                            <Grid
                                sx={{
                                    width: { xs: "100%", lg: "50%" },
                                    display: "flex",
                                    justifyContent: { xs: "flex-start", lg: "flex-end" },
                                    alignItems: "center",
                                    gap: 2,
                                    // px: 1,
                                    mt: { xs: 2, lg: 0 }
                                }}
                            >
                                <Button variant="contained" fullWidth onClick={quickAddBalance}>
                                    Quick Add {isIndian ? '₹' : '$'}{totalAmount}
                                </Button>

                                <Button variant="contained" fullWidth onClick={handleExport}>
                                    Export
                                </Button>
                            </Grid>

                        </Grid>
                    )}
                    {rows.length > 0 && (
                        <Box sx={{ width: "100%", mt: 3 }}>
                            <DataGrid
                                autoHeight
                                rows={rows}
                                // getRowId={(row) => row.id}
                                columns={columns}
                                pageSizeOptions={[5, 10, 20]}
                                initialState={{
                                    pagination: { paginationModel: { pageSize: 5 } },
                                }}
                                disableRowSelectionOnClick
                                sx={{
                                    width: "100%",
                                    border: "none",

                                    /* increase spacing inside cells */
                                    "& .MuiDataGrid-cell": {
                                        // padding: "12px 16px",
                                        fontSize: "14px",
                                    },

                                    /* increase spacing in header */
                                    "& .MuiDataGrid-columnHeader": {
                                        // padding: "12px 16px",
                                        fontWeight: "600",
                                        // background: "#f8f8f8",
                                    },

                                    /* remove outlines */
                                    "& .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" },

                                    /* remove selection coloration */
                                    "& .MuiDataGrid-row.Mui-selected": {
                                        backgroundColor: "transparent !important",
                                    },
                                    "& .MuiDataGrid-row.Mui-selected:hover": {
                                        backgroundColor: "transparent !important",
                                    },
                                }}
                            />
                        </Box>
                    )}

                    <Dialog
                        open={openEditModal}
                        onClose={() => setOpenEditModal(false)}
                        fullWidth
                        maxWidth="sm"
                    >
                        <DialogTitle>Edit Log Time</DialogTitle>

                        <DialogContent sx={{ mt: 2 }}>
                            {selectedRow && (
                                <>
                                    <br />
                                    <MobileDateTimePicker
                                        enableAccessibleFieldDOMStructure={false}
                                        label="Update Time"
                                        value={editDateTime}
                                        onChange={(newValue) => setEditDateTime(newValue)}
                                        slots={{ textField: CustomTextField }}
                                        minutesStep={1}
                                        timeSteps={{ minutes: 1 }}
                                        slotProps={{
                                            textField: {
                                                fullWidth: true,
                                                size: "small",
                                                variant: "outlined",
                                            },
                                        }}
                                    />
                                </>
                            )}
                        </DialogContent>

                        <DialogActions>
                            <Button onClick={() => setOpenEditModal(false)}>Cancel</Button>
                            <Button
                                variant="contained"
                                onClick={handleUpdateTime}
                                disabled={isLoading}
                            >
                                {isLoading ? 'Updating...' : 'Update'}
                            </Button>
                        </DialogActions>
                    </Dialog>
                    <Dialog open={openDeleteModal} onClose={() => setOpenDeleteModal(false)} >
                        <DialogTitle>Delete Time</DialogTitle>
                        <DialogContent>
                            <Typography sx={{ mt: 1 }}>
                                Are you sure you want to delete this time?
                            </Typography>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setOpenDeleteModal(false)}>Cancel</Button>
                            <Button variant="contained" color="error" onClick={handleDeleteTime}
                                disabled={isLoading}

                            >
                                {isLoading ? 'Deleting...' : 'Yes, Delete'}

                            </Button>
                        </DialogActions>
                    </Dialog>
                </BaseCard>

            </Box>
        </PageContainer >
    );
}