import React, { useState, useEffect, useCallback } from "react";
import PropTypes from "prop-types";
import { activityPageDropdown, activityPage } from "../constants/apiEndPoints.js";
import useApiService from "../services/apiService.js";
import Loader from "../components/Loader.js";
import CommonTable from "../components/CommonTable.js";
import { Button, Tooltip, Grid } from "@mui/material";
import DropdownMenu from "../utils/Dropdown.js";
import SearchInput from "../components/SearchInput.js";
import DateFilterDropdown from "../components/DateFilterDropdown.js";
import { FilterAltOff } from "@mui/icons-material/";
import { getTodayDateRange } from "../constants/dateUtils.js";
import "./Dashboard.css";

function ActivityTable({ employeeId, title }) {
  const { postApi, getApi } = useApiService();
  const isUserProfileTab = title === "userProfile";

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [dropDownData, setDropDownData] = useState([]);
  const [activityState, setActivityState] = useState(null);
  const [searchTextState, setSearchTextState] = useState("");
  const [selectedRange, setSelectedRange] = useState(getTodayDateRange());

  const initialFilter = {
    SearchText: employeeId || null,
    PageSize: 50,
    PageNumber: 1,
    IgnorePaging: false,
    Filter: {
      Activity: activityState,
      LoginTime: selectedRange.startDate,
      LogoutTime: selectedRange.endDate,
    },
    SortOrder: "DESC",
    SortColumn: "",
  };

  const [filter, setFilter] = useState(initialFilter);

  // =========================
  // Dropdown API
  // =========================

  const fetchDataDropdown = async () => {
    try {
      setLoading(true);
      const response = await getApi(activityPageDropdown);
      setDropDownData(response?.length ? response : []);
    } catch (error) {
      console.error("Error fetching dropdown data:", error);
      setDropDownData([]);
    } finally {
      setLoading(false);
    }
  };

  const getData = useCallback(async (dataObj) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...dataObj };
      setFilter(updatedFilterData);
      const result = await postApi(activityPage, updatedFilterData);
      setData(result || []);
    } catch (error) {
      console.error("Error fetching activity data:", error);
    } finally {
      setLoading(false);
    }
  }, [filter, postApi]);

  useEffect(() => {
    const initializeData = async () => {
      await fetchDataDropdown();
      getData({});
    };
    initializeData();
  }, []);

  // =========================
  // Handlers
  // =========================

  const handleSearch = (searchText) => {
    setSearchTextState(searchText);
    const updatedFilters = {
      ...filter,
      SearchText: searchText.toLowerCase(),
    };
    getData(updatedFilters);
  };

  const handleDateFilterChange = (filterType, dateRange) => {
    setSelectedRange(dateRange);

    const updatedDateFilter = {
      SearchText: employeeId || searchTextState || null,
      PageSize: 50,
      PageNumber: 1,
      IgnorePaging: false,
      Filter: {
        Activity: activityState,
        LoginTime: dateRange?.startDate,
        LogoutTime: dateRange?.endDate,
      },
    };

    getData(updatedDateFilter);
  };

  const resetDateRangeSelector = () => {
    setSelectedRange({ startDate: null, endDate: null });
    setActivityState(null);
    setSearchTextState("");

    const updatedFilter = {
      ...filter,
      SearchText: "",
      SortColumn: "",
      SortOrder: "DESC",
      Filter: {
        Activity: null,
        LoginTime: null,
        LogoutTime: null,
      },
    };

    setFilter(updatedFilter);
    getData(updatedFilter);
  };

  const handleClear = () => {
    setSearchTextState("");

    const updatedFilters = {
      ...filter,
      SearchText: "",
      Filter: {
        Activity: null,
        LoginTime: null,
        LogoutTime: null,
      },
    };

    getData(updatedFilters);
  };

  // =========================
  // Columns
  // =========================

  const columns = [
    { field: "EmployeeName", headerName: "Employee", type: String, flex: 3 },
    { field: "IpAddress", headerName: "IP Address", type: String, flex: 2 },
    { field: "SystemStatus", headerName: "System Status", type: String, flex: 2 },
    { field: "LoginTime", headerName: "Login Time", type: Date, flex: 2 },
    { field: "LogoutTime", headerName: "Logout Time", type: Date, flex: 2 },
    { field: "UpdatedOn", headerName: "Updated On", type: Date, flex: 2 },
  ];

  // =========================
  // UI
  // =========================

  return (
    <>
      {!isUserProfileTab && (
        <div className="widgets">
          <div className="widgets-left">
            <Grid container spacing={2} alignItems="center">
              <Grid item>
                <DropdownMenu
                  label="Alert Type"
                  value={activityState || "Active"}
                  onSelectChange={(value) => {
                    setActivityState(value);

                    const updatedFilter = {
                      ...filter,
                      SearchText: employeeId || searchTextState || null,
                      Filter: {
                        ...filter.Filter,
                        Activity: value,
                        LoginTime: selectedRange.startDate,
                        LogoutTime: selectedRange.endDate,
                      },
                    };

                    getData(updatedFilter);
                  }}
                  dropDownData={dropDownData}
                  dropDownKeys={{ id: "Id", name: "Name" }}
                  sx={{ minWidth: 100, maxWidth: 150 }}
                />
              </Grid>
            </Grid>

            <DateFilterDropdown
              onChange={handleDateFilterChange}
              isRangePicker
            />

            <Tooltip title="Clear filters">
              <Button
                className="clear-btn"
                variant="outlined"
                onClick={resetDateRangeSelector}
                color="error"
              >
                <FilterAltOff />
              </Button>
            </Tooltip>
          </div>

          <div className="search-download">
            <div className="other-filters">
              {!employeeId && (
                <SearchInput
                  onClear={handleClear}
                  onSearch={handleSearch}
                  textToSearch={searchTextState}
                />
              )}
            </div>
          </div>
        </div>
      )}

      <div className="activityTable">
        {loading && <Loader />}
        <CommonTable
          data={data}
          component="Activity"
          columns={columns}
          onChange={getData}
          filters={filter}
          containerHeight={
            isUserProfileTab ? "calc(100vh - 420px)" : undefined
          }
        />
      </div>
    </>
  );
}

ActivityTable.propTypes = {
  employeeId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  title: PropTypes.string,
};

ActivityTable.defaultProps = {
  employeeId: null,
  title: "",
};

export default ActivityTable;