"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 } 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 Calendar from "./calendar/index";

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

  // --- 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'));

  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])
  useEffect(() => {
    if (user && user.role !== "Super") {
      router.push("/dashboard");
    }
  }, [user]);
  return (
    <PageContainer title={'Calendar - 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="Calendar">
          {/* <Box sx={{ width: "100%" }}> */}
          <Calendar sessionData={sessionData} />
          {/* </Box> */}
        </BaseCard>
      </Box>
    </PageContainer >
  );
}