"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 } 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],
    },
}));

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>('');
    // --- Filter States ---
    const [selectedEmployee, setSelectedEmployee] = useState<any | null>(null);
    const [inputValue, setInputValue] = useState('');

    const [fromDate, setFromDate] = useState<Dayjs | null>(dayjs().startOf('day'));
    const [toDate, setToDate] = useState<Dayjs | null>(dayjs().endOf('day'));
    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) => ({
                    id: index + 1,
                    logtime: item.logtime,
                    type: item.type
                }))
            );
        } else {
            setRows([]);
        }
    }, [logins]);
    const columns = [
        {
            field: "logtime",
            headerName: "Time",
            flex: 1,
            renderCell: (params: any) => (
                <span style={{ fontWeight: 700 }}>
                    {formatWithMoment(params.value)}
                </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>
            )
        },
    ];
    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,
            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,
                from: fromDate?.format('YYYY-MM-DD HH:mm:ss'),
                to: toDate?.format('YYYY-MM-DD HH:mm:ss')
            }
            const response = await axios.post('/api/employeeLogins', payload)
            if (response?.data?.status !== 'error') {
                setLogins(response?.data?.data)
                setSuccess(`Data fetched for: ${selectedEmployee?.username}`)
                setTotalTime(response?.data?.total_time)
                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]);
    return (
        <PageContainer title={'Employee Logins - 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 Logins">
                    {isLoading && <><LinearProgress /><br /></>}

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


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

                                gridTemplateColumns: {
                                    xs: '1fr',
                                    md: '1fr 1fr',
                                    lg: 'repeat(4, 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"
                                        />
                                    )}
                                />


                                <MobileDateTimePicker
                                    label="From Date"
                                    value={fromDate}
                                    onChange={(newValue) => setFromDate(newValue)}
                                    slots={{ textField: CustomTextField }}
                                    slotProps={{
                                        textField: {
                                            fullWidth: true,
                                            size: 'small',
                                            variant: 'outlined'
                                        }
                                    }}
                                />


                                <MobileDateTimePicker
                                    label="To Date"
                                    value={toDate}
                                    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 && (
                        <Box sx={{ width: '100%', mt: 3 }}>
                            <Typography sx={{ fontSize: 22, fontWeight: 'bold', ml: 1 }}>Total Hours: {`${totalTime?.hours} Hours ${totalTime?.minutes} Minutes`}</Typography>
                        </Box>
                    )}
                    {rows.length > 0 && (
                        <Box sx={{ width: "100%", mt: 3 }}>
                            <DataGrid
                                autoHeight
                                rows={rows}
                                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>
                    )}


                    {/* {rows.length === 0 && (
                        <Typography sx={{ p: 2, textAlign: "center" }}>No logins found</Typography>
                    )} */}

                </BaseCard>
            </Box>
        </PageContainer >
    );
}