import React, { useState, useEffect } from "react";
import { getAuditLogs } from "../constants/apiEndPoints.js";
import useApiService from "../services/apiService.js";
import PropTypes from "prop-types";
import Loader from "../components/Loader.js";
import CommonTable from "../components/CommonTable.js";
import SearchInput from "../components/SearchInput.js";
import DateFilterDropdown from "../components/DateFilterDropdown.js";
import { getTodayDateRange } from "../constants/dateUtils.js";
import "../pages/Dashboard.css";

function AuditLogs(props) {
  const { postApi } = useApiService();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [searchTextState, setSearchTextState] = useState("");
  const [selectedRange, setSelectedRange] = useState(getTodayDateRange());
  let dataObj = {
    SearchText: "",
    PageSize: 50,
    PageNumber: 1,
    IgnorePaging: false,
    Filter: {
      StartDate: selectedRange.startDate || null,
      EndDate: selectedRange.endDate || null,
    },
  };

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

  const columns = [
    { field: "table_name", headerName: "Section", type: String, flex: 3 },
    {
      field: "operation_type",
      headerName: "Operation Type",
      type: String,
      flex: 2,
    },
    { field: "UserName", headerName: "Action On", type: String, flex: 2 },
    { field: "changed_by", headerName: "Changed By", type: String, flex: 2 },
    { field: "updated_on", headerName: "Updated On", type: Date, flex: 2 },
  ];

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

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

  useEffect(() => {
    getData({});
  }, []);

  const handleDateFilterChange = (filterType, dateRange) => {
    setSelectedRange(dateRange);
    const updatedDateFilter = {
      SearchText: searchTextState,
      PageSize: 50,
      PageNumber: 1,
      IgnorePaging: false,
      Filter: {
        StartDate: dateRange?.startDate,
        EndDate: dateRange?.endDate,
      },
    };
    getData(updatedDateFilter);
  };

  const handleClear = () => {
    setSearchTextState("");
    const updatedFilters = {
      ...filter,
      SearchText: "",
      Filter: {
        StartDate: filter.Filter.StartDate || null,
        EndDate: filter.Filter.EndDate || null,
      },
    };
    getData(updatedFilters);
  };

  return (
    <>
      <div className="inner-container">
        <div className="filters-wrapper">
          <DateFilterDropdown onChange={handleDateFilterChange} isRangePicker={true} selectedRange={selectedRange} />

          <div className="other-filters">
            {!props.employeeId && (
              <SearchInput onClear={handleClear} onSearch={handleSearch} />
            )}
          </div>
        </div>
      </div>
      <div className="activityTable">
        {loading && <Loader />}
        <CommonTable
          data={data}
          component="Auditlogs"
          columns={columns}
          onChange={getData}
          filters={filter}
        />
      </div>
    </>
  );
}

AuditLogs.propTypes = {
  employeeId: PropTypes.number,
};
export default AuditLogs;

