import React, { useEffect, useState, useCallback, useRef } from 'react'
import CommonTable from '../../components/CommonTable.js';
import { systemSleepDetailsApi } 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 PropTypes from 'prop-types';
import Loader from '../../components/Loader.js';
import "../Dashboard.css";

 
function SystemSleepDetails(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({
    "SearchText": searchTextOnly || props.EmployeeName || props.summaryFilter?.EmpCode,
    "PageSize": 50,
    "PageNumber": 1,
    "IgnorePaging": false,
    "Filter": {
      "TriggeredOn": props.summaryFilter?.CallDate?.startDate || initialRange.startDate,
      "TriggeredOff": props.summaryFilter?.CallDate?.endDate || initialRange.endDate,
      "Description": "",
      "ResultsFor": props.summaryFilter?.ResultsFor || null,
    },
    "SortOrder": "DESC",
    "SortColumn": ""
  })

  // 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(systemSleepDetailsApi, updatedFilterData);
      setData(result || []);
    } catch (error) {
      console.warn("Error fetching system sleep details:", error);
      setData([]);
    } finally {
      setLoading(false);
    }
  }, [filter, postApi]);

  useEffect(() => {
    if (!hasInitialized.current) {
      hasInitialized.current = true;
      getData({});
    }
  }, [getData]);
 
  const handleDateFilterChange = (filterType, dateRange) => {
    const updatedFilter = {
      "SearchText": searchTextOnly || props.EmployeeName || props.summaryFilter?.EmpCode,
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "TriggeredOn": dateRange?.startDate,
        "TriggeredOff": dateRange?.endDate,
        "Description": ""
      }
    };
    getData(updatedFilter);
  };

  const handleClear = () => {
    setSelectedRange({ startDate: null, endDate: null });
    setSearchTextOnly('');
    const updatedFilter = {
      ...filter,
      SearchText: "",
      Filter: {
        TriggeredOn: null,
        TriggeredOff: null,
        Description: "",
        ResultsFor: null,
      }
    }
    getData(updatedFilter)
  }

    const handleSearch = (searchText) => {
          setSearchTextOnly(searchText); 
  
      
        const updatedFilters = {
          ...filter,
          SearchText: searchText.toLowerCase(),  // Ensure the search text is in lowercase
        };
        getData(updatedFilters);  // Trigger the data fetch
    };

  
  useEffect(() => {
    if (props.title === "userProfile") {
      setColumns(
        [
          
          { field: 'Description', headerName: 'Description', type: String, flex: 3  },
          { field: 'TriggeredOn', headerName: 'Triggered on', type: Date, flex: 2  },
          { field: 'UpdatedOn', headerName: 'Updated on', type: Date, flex: 2  },
        ]);
    } else {
      setColumns([
        { field: 'EmployeeName', headerName: 'Employee', type: String, flex: 3  },
        { field: 'Description', headerName: 'Description', type: String, flex: 3  },
        { field: 'TriggeredOn', headerName: 'Triggered On', type: Date, flex: 2  },
        { field: 'UpdatedOn', headerName: 'Updated on', type: Date, flex: 2  },


      ]);
    }

  }, [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={data} cols={cols} columns={columns} defaultSortColumn="" onChange={getData} filters={filter} />
      {loading && <Loader />}
    </div>
  </div>
}


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

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


export default SystemSleepDetails;
