import React, { useEffect, useState, useCallback,useRef } from "react";
import {
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Typography,
  Fade,
  Grid,
} from "@mui/material";
import { ExpandMore } from "@mui/icons-material";
import { format } from "date-fns";
import PropTypes from "prop-types";
import moment from "moment";

import useApiService from "../services/apiService.js";
import LineChart from "../components/LineChart.js";
import Widgets from "../components/Widgets.js";
import DashboardTable from "../components/DashboardTable.js";

import Loader from "../components/Loader.js";
import TopUsersScreen from "./TopUsersScreen.js";
import BottomUsersScreen from "./BottomUsersScreen.js";

import {
  dashboardTableApi,
  graphApi,
  top10bottom10,
} from "../constants/apiEndPoints.js";

import secondToTimeConverter from "../utils/secondToTime.js";

import stopwatch from "../assets/svg/stopwatch.png";
import group from "../assets/svg/group.png";
import active from "../assets/svg/active-user.png";

import "./Dashboard.css";

function Dashboard({ title }) {
  const { postApi } = useApiService();
  const [expanded, setExpanded] = useState(true);
  const [loading, setLoading] = useState(false);
  const [graphData, setGraphData] = useState([]);
  const [selectedDate, setSelectedDate] = useState(new Date());

  const [data, setData] = useState([]);
  const [topBottomData, setTopBottomData] = useState([]);
  const [activityLabel, setActivityLabel] = useState("");
  const formattedCurrentDate = format(new Date(), "dd-MM-yyyy");

  const handleExpansion = () => {
    setExpanded((prev) => !prev);
  };

  const handleDateFilterChange = useCallback(
    (filterType, dateData) => {
      let dateValue;
      if (dateData?.startDate instanceof Date) {
        dateValue = dateData.startDate;
      } else if (dateData instanceof Date) {
        dateValue = dateData;
      } else {
        dateValue = new Date();
      }

      setSelectedDate(dateValue);

      const formattedSelected = format(dateValue, "MM/dd/yyyy");
      const formattedToday = format(new Date(), "MM/dd/yyyy");

      const updatedFilter = {
        SearchText: "",
        PageSize: 10,
        PageNumber: 1,
        IgnorePaging: false,
        Filter: {
          RequestStartDate: dateValue,
          RequestEndDate: new Date(dateValue.getTime() + 86400000),
          IsLiveData: formattedSelected === formattedToday,
        }};
      const dateFilterForGraph = {
        SearchText: "",
        PageSize: 10,
        PageNumber: 1,
        IgnorePaging: false,
        Filter: {
          RequestTime: dateValue,
          IsLiveData: false,
        }
      };

      setActivityLabel(
        formattedSelected === formattedToday
          ? "Activity: Today"
          : `Activity: ${formattedSelected}`
      );

      fetchGraphData(dateFilterForGraph);
      fetchTableData(updatedFilter);
      fetchTopBottomUsers(dateValue);
    },
    [] // Remove baseFilter from dependencies to prevent circular updates
  );

  const fetchGraphData = async (filterData) => {
    setLoading(true);
    try {
      const result = await postApi(graphApi, filterData);
      setGraphData(result?.Records || []);
    } catch (error) {
      console.error("Graph API error:", error);
    } finally {
      setLoading(false);
    }
  };

  const fetchTableData = async (filterData) => {
    setLoading(true);
    try {
      const result = await postApi(dashboardTableApi, filterData);
      setData(result?.Records || []);
    } catch (error) {
      console.error("Table API error:", error);
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  const fetchTopBottomUsers = async (dateValue) => {
    setLoading(true);
    try {
      const result = await postApi(top10bottom10, {
        EmpCode: null,
        StartedOn: moment(dateValue).format(),
      });
      setTopBottomData(result?.Records?.[0] || {});
    } catch (error) {
      console.error("Top/Bottom API error:", error);
    } finally {
      setLoading(false);
    }
  };


  // Use useRef to ensure initialization only happens once
  const hasInitialized = useRef(false);
  
  useEffect(() => {
    if (!hasInitialized.current) {
      hasInitialized.current = true;
      handleDateFilterChange("Today", new Date());
    }
  }, [handleDateFilterChange]);

  const totalUsageSeconds = data?.[0]?.TotalUsageCount || 0;
  const totalUsageFormatted = secondToTimeConverter(totalUsageSeconds);
  const totalUsers = data?.[0]?.TotalUsers || 0;
  const totalActiveUsers = data?.[0]?.TotalActiveUsers || 0;
  const todayActiveUsers = data?.[0]?.TotalActiveUsersToday || 0;

  const columns = [{ id: "Device", label: "Device", type: Number }];

  return (
    <>
      <div className="outer-body">
        <div className="title-box d-flex top-filter">
          <h2>{title}</h2>
          <div className="date-display new ">
            Data displayed for <strong>{formattedCurrentDate}</strong>
          </div>
        </div>
      </div>

      <Grid container spacing={3} className="widgets">
        <Grid item xs={12} sm={6} md={4}>
          <Widgets
            title="Active / Today's Active Users"
            number={`${totalActiveUsers} / ${todayActiveUsers}`}
            Icons={active}
            className="firstwidget actv-User"
          />
        </Grid>

        <Grid item xs={12} sm={6} md={4}>
          <Widgets
            title="All Users"
            number={totalUsers}
            Icons={group}
            className="secondwidget all-user"
          />
        </Grid>

        <Grid item xs={12} sm={6} md={4}>
          <Widgets
            title="Usage Time"
            number={totalUsageFormatted}
            Icons={stopwatch}
            className="thirdwidget total-usage-time"
          />
        </Grid>
      </Grid>

      <Accordion
        expanded={expanded}
        onChange={handleExpansion}
        slots={{ transition: Fade }}
        className="accordion-section"
      >
        <AccordionSummary expandIcon={<ExpandMore />}>
          <Typography variant="h6">
            {activityLabel && <strong>{activityLabel}</strong>}
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <div style={{ width: "100%" }}>
            <LineChart graphData={graphData} />
          </div>
        </AccordionDetails>
      </Accordion>

      <div className="topscreens">
        <BottomUsersScreen
          isAutoHeight
          data={topBottomData}
          selectedDate={selectedDate}
        />
        {loading && <Loader />}
      </div>

      <div className="topscreens">
        <TopUsersScreen
          isAutoHeight
          data={topBottomData}
          selectedDate={selectedDate}
        />
        {loading && <Loader />}
      </div>

      <Accordion defaultExpanded className="accordion-section">
        <AccordionSummary expandIcon={<ExpandMore />}>
          <Typography variant="h6">
            <strong>Account Overview</strong>
          </Typography>
        </AccordionSummary>
        <AccordionDetails>
          <div style={{ width: "100%" }}>
            <DashboardTable Columns={columns} data={data} />
          </div>
        </AccordionDetails>
      </Accordion>
    </>
  );
}

Dashboard.propTypes = {
  title: PropTypes.string.isRequired,
};

export default Dashboard;