import React, { useEffect, useState, useCallback, useRef } from 'react'
import CommonTable from '../../components/CommonTable.js';
import { employeeWorkingTimeApi } from "../../constants/apiEndPoints.js";
import SearchInput from '../../components/SearchInput.js';
import DateFilterDropdown from '../../components/DateFilterDropdown.js';
import { getTodayDateRange } from '../../constants/dateUtils.js';
import useApiService from "../../services/apiService.js"
import Loader from '../../components/Loader.js';
import propTypes from 'prop-types';
import { commonFilterActivityLogs } from '../../constants/defaultFilters.js';
import "../Dashboard.css";


function EmployeeWorkingTime(props) {
  const { postApi } = useApiService()
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [searchTextOnly, setSearchTextOnly] = useState();
  const initialRange = getTodayDateRange();
  const [selectedRange, setSelectedRange] = useState(initialRange);

  const [filter, setFilter] = useState({
    ...commonFilterActivityLogs,
    SearchText: props?.employeeId || null,
    Filter: {
      "WorkLoggedOn": props.summaryFilter?.CallDate?.startDate || initialRange.startDate,
      "WorkEndedOn": props.summaryFilter?.CallDate?.endDate || initialRange.endDate,
      "ResultsFor": props.summaryFilter?.ResultsFor || null
    },
  })

  // Use useRef to prevent multiple initializations
  const hasInitialized = useRef(false);

  const getData = useCallback(async (updatedFilter) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...updatedFilter };
      setFilter(updatedFilterData);
      const result = await postApi(employeeWorkingTimeApi, updatedFilterData);
      setData(result || []);
    } catch (error) {
      console.warn("Error fetching employee working time:", error);
      setData([]);
    } finally {
      setLoading(false);
    }
  }, [filter, postApi]);

  const handleDateFilterChange = useCallback((filterType, dateRange) => {
    setSelectedRange(dateRange);
    const updatedFilter = {
      "SearchText": searchTextOnly || props?.employeeId || null,
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "WorkLoggedOn": dateRange?.startDate,
        "WorkEndedOn": dateRange?.endDate,
        "EmpCode": searchTextOnly || props?.employeeId || null
      }
    };
    getData(updatedFilter);
  }, [searchTextOnly, props?.employeeId, getData]);

  useEffect(() => {
    if (!hasInitialized.current) {
      hasInitialized.current = true;
      getData({});
    }
  }, [getData]);
  const handleClear = () => {
    setSelectedRange({ startDate: null, endDate: null });
    setSearchTextOnly('');
    const updatedFilter = {
      ...filter,
      SearchText: "",
      Filter: {
        WorkLoggedOn: null,
        WorkEndedOn: null
      }
    };
    setFilter(updatedFilter);
    getData(updatedFilter);
  }

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

    getData(updatedFilters);
  };

  // Update the search text state



  useEffect(() => {

    if (props.title === "userProfile") {
      setColumns(
        [

          { field: 'TotalActive', headerName: 'Total Active', type: Number, flex: 2 },
          { field: 'TotalIdle', headerName: 'Total Idle', type: Number, flex: 2 },
          { field: 'TotalSleep', headerName: 'Total Sleep', type: Number, flex: 2 },
          { field: 'WorkLoggedOn', headerName: 'Work Logged on', type: Date, flex: 2.5 },
          { field: 'UpdatedOn', headerName: 'Work Updated On', type: Date, flex: 2.5 },
          { field: 'Location', headerName: 'Location', type: String, flex: 2 },


        ]);
    } else {
      setColumns([
        { field: 'EmployeeName', headerName: 'Employee', type: String, flex: 2 },
        { field: 'Location', headerName: 'Location', type: String, flex: 2 },
        { field: 'TotalActive', headerName: 'Total Active', type: Number, flex: 2 },
        { field: 'TotalIdle', headerName: 'Total Idle', type: Number, flex: 2 },
        { field: 'TotalSleep', headerName: 'Total Sleep', type: Number, flex: 2 },
        { field: 'WorkLoggedOn', headerName: 'Work Logged on', type: Date, flex: 2.5 },
        { field: 'UpdatedOn', headerName: 'Work Updated On', type: Date, flex: 2.5 },


      ]);
    }
  }, [props.title]);


  const cols = {
    field: 'EmpCode', headerName: 'Employee', type: String, flex: 3
  };


  return <div className='inner-container'>
    <div className='filters-wrapper'>
      <DateFilterDropdown
        onChange={handleDateFilterChange}
        isRangePicker={true}
        selectedRange={selectedRange}
      />
      <div className='other-filters' >
        {!props.employeeId && <SearchInput onSearch={handleSearch} onClear={handleClear} />}
      </div>
    </div>
    <div >
      <CommonTable data-testid="common-table" cols={cols} data={data} columns={columns} defaultSortColumn="" onChange={getData} filters={filter} />
      {loading && <Loader data-testid="loader" />}
    </div>
  </div>
}

EmployeeWorkingTime.propTypes = {
  employeeId: propTypes.oneOfType([propTypes.string, propTypes.number]),
  title: propTypes.string,
  summaryFilter: propTypes.shape({
    CallDate: propTypes.shape({
      startDate: propTypes.instanceOf(Date),
      endDate: propTypes.instanceOf(Date),
    }),
    ResultsFor: propTypes.string,
  }),
};

export default EmployeeWorkingTime;
