import React, { useEffect, useState, useCallback, useRef } from 'react'
import CommonTable from '../../components/CommonTable.js';
import { systemLoginDetailsApi } 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 SystemLoginDetails(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 || null,
    "PageSize": 50,
    "PageNumber": 1,
    "IgnorePaging": false,
    "Filter": {
      "EmpCode": props.summaryFilter?.EmpCode || searchTextOnly|| props.EmployeeName || null,
      "LoginTime": props.summaryFilter?.CallDate?.startDate || initialRange.startDate,
      "LogoutTime": props.summaryFilter?.CallDate?.endDate || initialRange.endDate,
      "ResultsFor": props.summaryFilter?.ResultsFor || null
    },
    "SortOrder": "DESC",
    "SortColumn": null
  })

  // Use useRef to ensure initialization only happens once
  const hasInitialized = useRef(false);

  const getData = useCallback(async (updatedFilter) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...updatedFilter };
      setFilter(updatedFilterData);
      const result = await postApi(systemLoginDetailsApi, updatedFilterData);
      setData(result || []);
    } catch (error) {
      throw new Error(`Failed to load system login details: ${error.message}`);
    } finally {
      setLoading(false);
    }
  }, [filter, postApi]);

  useEffect(() => {
    if (!hasInitialized.current) {
      hasInitialized.current = true;
      getData({});
    }
  }, [getData]);

  const handleClear = () => {
    setSelectedRange({ startDate: null, endDate: null });
    setSearchTextOnly('');
    const updatedFilter = {
      "SearchText": "",
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "EmpCode": props.summaryFilter?.EmpCode || null,
        "LoginTime": null,
        "LogoutTime": null
      }
    }
    getData(updatedFilter)
 }

  const handleDateFilterChange = (filterType, dateRange) => {
    setSelectedRange(dateRange);
    const updatedDateFilter = {
      "SearchText": searchTextOnly || props.EmployeeName || props.summaryFilter?.EmpCode || null,
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "EmpCode": searchTextOnly || props.EmployeeName || props.summaryFilter?.EmpCode || null,
        "LoginTime": dateRange?.startDate,
        "LogoutTime": dateRange?.endDate
      }
    };
    getData(updatedDateFilter);
  };
  const handleSearch = (searchText) => {
      setSearchTextOnly(searchText); // Update the state with the search text
      const updatedFilters = {
        ...filter,
        SearchText: searchText.toLowerCase(), // Convert to lowercase for uniformity
      };
  
      getData(updatedFilters); // Trigger the data fetch
  };

 

  useEffect(() => {
    if (props.title === "userProfile") {
      setColumns(
        [
          { field: 'Total_Login_Time', headerName: 'Total Time', type: Number, flex: 2  },
          { field: 'LoginTime', headerName: 'Login Time', type: Date, flex: 2  },
          { field: 'LogoutTime', headerName: 'Logout Time', type: Date, flex: 2  },
          { field: 'SystemStatus', headerName: 'System Status', type: String, flex: 2.5 },
          { field: 'IpAddress', headerName: 'IP Address', type: String, flex: 2  },
          { field: 'ComputerName', headerName: 'Computer Name', type: String, flex: 2.5  },
          { field: 'AppVersion', headerName: 'App Version', type: String, flex: 2  },
          
        ]);
    } else {
      setColumns([
        { field: 'EmployeeName', headerName: 'Employee', type: String, flex: 2  },
        { field: 'Total_Login_Time', headerName: 'Total Time', type: Number, flex: 2  },
        { field: 'LoginTime', headerName: 'Login Time', type: Date, flex: 2  },
        { field: 'LogoutTime', headerName: 'Logout Time', type: Date, flex: 2  },
        { field: 'SystemStatus', headerName: 'System Status', type: String, flex: 2.5  },
        { field: 'IpAddress', headerName: 'IP Address', type: String, flex: 2  },
        { field: 'ComputerName', headerName: 'Computer Name', type: String, flex: 2.5   },
        { field: 'AppVersion', headerName: 'App Version', type: String, 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><div>
        <CommonTable data={data} cols={cols} enableRowNumbers={true} columns={columns} defaultSortColumn="" onChange={getData} filters={filter} />
        {loading && <Loader />}
      </div></>
     
)};

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

SystemLoginDetails.defaultProps = {
  employeeId: null,
  EmployeeName: "",
  title: "",
  summaryFilter: {
    EmpCode: null,
    CallDate: {
      startDate: null,
      endDate: null
    },
    ResultsFor: ""
  },
};


export default SystemLoginDetails;
