import React, { useEffect, useState, useRef } from 'react'
import { format } from 'date-fns';
import { Box } from '@mui/material';
import PropTypes from 'prop-types';
import CommonTable from '../components/CommonTable.js';
import  {getBrowsingDetails}  from "../constants/apiEndPoints.js";
import SearchInput from '../components/SearchInput.js';
import SmartDateSelector from "../components/SmartDateSelector.js";
import useApiService from "../services/apiService.js"
import Loader from '../components/Loader.js';
import { getTodayDateRange } from '../constants/dateUtils.js';
import "./Dashboard.css";

function BrowsingHistory(props) {
  const { postApi } = useApiService()
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [searchTextOnly, setSearchTextOnly]= useState()
  const [selectedRange, setSelectedRange] = useState(getTodayDateRange());
  const [filter, setFilter] = useState({
      "SearchText": props?.employeeId || null,
      "PageSize": 10,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "EmpCode": props?.employeeId || null,
        "StartedOn": props.summaryFilter?.CallDate?.startDate || null,
        "EndedOn": props.summaryFilter?.CallDate?.endDate || null,
        "Description": null,
        "ResultsFor": props.summaryFilter?.ResultsFor || null,
      },
      "SortOrder": null,
      "SortColumn": null
    }
  )

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

  const getData = async (updatedFilter) => {
   setLoading(true);
try {
  const updatedFilterData = { ...filter, ...updatedFilter };
  setFilter(updatedFilterData);
  const result = await postApi(getBrowsingDetails, updatedFilterData);
  setData(result || []);
} catch (error) {
  throw new Error(`Error fetching browsing details: ${error.message}`);
} finally {
  setLoading(false);
}
  };

  const handleDateSelectorApply = (dateRange) => {
    setSelectedRange(dateRange);
    
    const updatedDateFilter = {
      "SearchText": searchTextOnly|| props?.employeeId || null,
      "PageSize": 10,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "EmpCode": props?.employeeId || null,
        "StartedOn": dateRange.startDate || null,
        "EndedOn": dateRange.endDate || null,
        "Description": null,
        "ResultsFor": props.summaryFilter?.ResultsFor || null,
      },
      "SortOrder": null,
      "SortColumn": null
    }
    getData(updatedDateFilter)
  };

  const handleSearch = (searchText) => {
    setSearchTextOnly(searchText)
    if(searchText?.length > 3 || searchText?.length == 0){
      const updatedFilters = {...filter, Filter: { Description: searchText.toLowerCase()},SearchText: Number.isNaN(searchText) ? null : searchText.toLowerCase()};
      getData(updatedFilters);
    }
   
  };
  useEffect(() => {
    if (props.title === "userProfile") {
      setColumns(
        [
          { field: 'application_name', headerName: 'Application Name', type: String, flex: 3  },
          { field: 'description', headerName: 'Description', type: String, flex: 3  },
          { field: 'started_on', headerName: 'Started on', type: Date, flex: 2  },
          { field: 'ended_on', headerName: 'Ended on', type: Date, flex: 2  },
        ]);
    } else {
      setColumns([
        { field: 'EmployeeName', headerName: 'Employee', type: String, flex: 3  },
        { field: 'application_name', headerName: 'Application Name', type: String, flex: 3  },
        { field: 'description', headerName: 'Description', type: String, flex: 3  },
        { field: 'started_on', headerName: 'Started on', type: Date, flex: 2  },
        { field: 'ended_on', headerName: 'Ended on', type: Date, flex: 2  },
     
      ]);
    }
    
  }, [props.title]);

  const cols ={
    id: 'emp_code', label: 'Employee', type: String, flex: 3 
  }


  return <div className='inner-container'>
          <div className='filters-wrapper'>
          <div className="datepicker" >
            <SmartDateSelector
              onApply={handleDateSelectorApply}
              useSingleDate={false}
              initialValue={selectedRange}
            />
          </div>
            <div className='other-filters'>
                {!props.employeeId && <SearchInput data-testid="search-input" onSearch={handleSearch} onClear={getData} />}
            </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>
}
BrowsingHistory.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
  }),
};

BrowsingHistory.defaultProps = {
  employeeId: null,
  title: '',
  summaryFilter: {
    CallDate: { startDate: null, endDate: null },
    ResultsFor: null,
  },
};


export default BrowsingHistory;
