"use client";
import React from "react";
import { useEffect, useState } from "react";

import { Grid, Box, Alert, Typography } from "@mui/material";
import PageContainer from "@/app/components/container/PageContainer";
// components
import YearlyBreakup from "@/app/components/dashboards/modern/YearlyBreakup";
import MonthlyEarnings from "@/app/components/dashboards/modern/MonthlyEarnings";
import TopCards from "@/app/components/dashboards/modern/TopCards";
import RevenueUpdates from "@/app/components/dashboards/modern/RevenueUpdates";
import EmployeeSalary from "@/app/components/dashboards/modern/EmployeeSalary";
import Customers from "@/app/components/dashboards/modern/Customers";
import Projects from "@/app/components/dashboards/modern/Projects";
import Social from "@/app/components/dashboards/modern/Social";
import SellingProducts from "@/app/components/dashboards/modern/SellingProducts";
import WeeklyStats from "@/app/components/dashboards/modern/WeeklyStats";
import TopPerformers from "@/app/components/dashboards/modern/TopPerformers";
import axios from "axios";
import { useRouter } from "next/navigation";
import { getSession } from '@/utils/sessionData';
import TopCardsNew from "../components/dashboards/modern/TopCardsNew";

export default function Dashboard() {
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
    setIsLoading(false);
  }, []);

  const router = useRouter();
  const checkSession = async () => {
    const session = getSession()
    if (!session?.admin_id && !session?.token) {
      router.push('/login')
    }
  }
  useEffect(() => {
    checkSession()
  }, [])
  // const { isLoading } = useGetAnalyticsDashboardWidgetsQuery();

  const [sessionData, setSessionData] = useState<any>();
  // const [isLoading, setIsLoading] = useState(false);
  const [kioskRunning, setKioskRunning] = useState<any>(false);
  const [kiosks, setKiosks] = useState<any>();
  const [dashData, setDashData] = useState<any>({
    totalDeposit: 0,
    billCount: 0,
    balance: 0
  })
  const [kioskData, setKioskData] = useState<any>({
    amountStacked: 0,
    notesStacked: 0

  });

  const fetchData = async () => {
    try {
      setIsLoading(true);
      const token = sessionData?.token;

      const response = await axios.post(`/api/getDashboardData`, { token });
      if (response?.data?.status !== 'error') {

        setDashData(response?.data?.data);
      }
    } catch (error: any) {
      console.error(error.message);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchKiosk = async () => {
    try {
      setIsLoading(true);
      const token = sessionData?.token;

      const response = await axios.post(`/api/getKioskStatus`, { token });
      console.log(response)

      if (response?.data?.error !== 'Something went wrong') {
        console.log(response?.data)
        setKioskData(response?.data)
        setKioskRunning(response?.data?.running)
        // setDashData(response?.data?.data);
      } else {
        console.log(response?.data)
        setKioskData({
          notesStacked: 0,
          amountStacked: 0
        })
      }
    } catch (error: any) {
      console.error(error.message);
    } finally {
      setIsLoading(false);
    }
  };

  // const fetchKiosks = async () => {
  //   try {
  //     setIsLoading(true);
  //     const token = sessionData?.token;

  //     const response = await axios.post(`/api/getKiosks`, { token });
  //     console.log(response)

  //     if (response?.data?.status != 'error') {
  //       console.log(response?.data)
  //       setKiosks(response?.data?.kiosks)
  //       console.log(response?.data?.kiosks?.map((kiosk: any) => { console.log(kiosk.kiosk_name) }))
  //       // setDashData(response?.data?.data);
  //     } else {
  //       console.log(response?.data)
  //       setKiosks([])
  //     }
  //   } catch (error: any) {
  //     console.error(error.message);
  //   } finally {
  //     setIsLoading(false);
  //   }
  // };
  useEffect(() => {
    const session = getSession();
    setSessionData(session);
  }, []);

  useEffect(() => {
    if (sessionData?.token && sessionData?.admin_id) {
      fetchData();
      fetchKiosk();
    }
  }, [sessionData?.token, sessionData?.admin_id]);

  return (
    (<PageContainer title="Dashboard" description="this is Dashboard">
      <Box >
        <Grid container spacing={3}>
          {/* column */}
          <Grid
            size={{
              xs: 12,
              lg: 12
            }}>
            {/* {kiosks?.map((kiosk: any) => {
              <Typography>{kiosk.kiosk_name}</Typography>
            })} */}
            <TopCardsNew
              receiverStatus={
                isLoading ? (
                  '...'
                ) : kioskRunning ? (
                  <Alert variant="filled" severity="success" className="text-white">
                    Active
                  </Alert>
                ) : (
                  <Alert variant="filled" severity="error">
                    Inactive
                  </Alert>
                )
              }
              kioskBalance={
                isLoading ? '...' : `$${kioskData && (parseInt(kioskData?.amountStacked) / 100)}`
              }
              kioskBillCount={
                isLoading ? '...' : `${kioskData && kioskData?.notesStacked}`
              }
              kioskTotalDeposits={
                isLoading ? '...' : `$${dashData && dashData?.totalDeposit}`
              }
            />
          </Grid>

        </Grid>

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