import React, { useEffect, useState, useRef } from 'react'
import CommonTable from '../../components/CommonTable.js';
import { runningApplicationsApi } 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 TableDataPopup from '../../components/TableDataPopup.js';
import "../Dashboard.css";


function RunningApplicationDetails(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 [applicationDetails, setApplicationDetails] = useState({})
  const [filter, setFilter] = useState(
    {
      "SearchText": "",
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "EmpCode": props?.employeeId || null,
        "StartedOn": props.summaryFilter?.CallDate?.startDate || initialRange.startDate,
        "EndedOn": props.summaryFilter?.CallDate?.endDate || initialRange.endDate,
        "ResultsFor": props.summaryFilter?.ResultsFor || null,
      },
      "SortOrder": null,
      "SortColumn": null
    }
  )
  const [showPopup, setShowPopup] = useState(false);
  
  const getData = async (updatedFilter = {}) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...updatedFilter };
      setFilter(updatedFilterData);
      const result = await postApi(runningApplicationsApi, updatedFilterData);
      setData(result || []);
    } catch (error) {
      console.error("Error fetching data:", error.message);
    } finally {
      setLoading(false);
    }
  };
  
  // Only run initial fetch once on component mount
  const hasInitializedRef = useRef(false);
  
  useEffect(() => {
    if (!hasInitializedRef.current) {
      hasInitializedRef.current = true;
      getData(filter);
    }
  }, []); // Empty dependency array for one-time initialization
  
 const handleClear =() => {
    setSelectedRange({ startDate: null, endDate: null });
    setSearchTextOnly('');
    const updatedFilter = {
      ...filter,
      SearchText: searchTextOnly || props.EmployeeName || null,
      Filter: {
        EmpCode: props.EmployeeName || null,
        StartedOn: null,
        EndedOn: null,
        ResultsFor: null,
      },
    };
    getData(updatedFilter);
 }

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

   const handleSearch = (searchText) => {
  
      setSearchTextOnly(searchText);
      const searchEmp = searchText.toLowerCase();
      const updatedFilters = {
        SearchText: searchEmp,
        PageSize: 50,
        PageNumber: 1,
        IgnorePaging: false,
        Filter: {
          EmpCode: props.EmployeeName || searchEmp || null,
          StartedOn: selectedRange?.startDate || null,
          EndedOn: selectedRange?.endDate || null,
          ResultsFor: null,
        },
        SortOrder: null,
        SortColumn: null,
      };
  
      getData(updatedFilters); // Trigger the data fetch
  };
  
  useEffect(() => {
    if (props.title === "userProfile") {
      setColumns(
        [
          { field: 'application_name', headerName: 'Application Name', type: String, flex: 2  },
          { field: 'application_count', headerName: 'Application Count', type: String, flex: 2  },
          { field: 'StartedOn', headerName: 'Started on', type: Date, flex: 2  },
          { field: 'browsing_time', headerName: 'Browsing Time', type: Number, flex: 2 },
        ]);
    } else {
      setColumns([
        { field: 'EmployeeName', headerName: 'Employee', type: String, flex: 2  },
        { field: 'application_name', headerName: 'Application Name', type: String, flex: 2  },
        { field: 'application_count', headerName: 'Application Count', type: String, flex: 2  },
        { field: 'StartedOn', headerName: 'Started on', type: Date, flex: 2  },
        { field: 'browsing_time', headerName: 'Browsing Time', type: Number, flex: 2  },

      ]);
    }

  }, [props.title]);

  const columnForPopup = [
    { field: 'description', headerName: 'Description', type: String, flex: 4  },
    { field: 'TotalBrowsingTime', headerName: 'Duration', type: Number, flex: 2  },
    { field: 'StartedOn', headerName: 'Started on', type: Date, flex: 2  },
    { field: 'EndedOn', headerName: 'Ended on', type: Date, flex: 2  },
]

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

  const togglePopup = (emp_code, application_name) => {
    setApplicationDetails({emp_code, application_name})
    setShowPopup(!showPopup);
  };

  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 >
      {
        showPopup && (
          <div className='popup' style={{backgroundColor:"rgba(0,0,0,0.7) !important"}} >
            <TableDataPopup data-testid="toggle-popup-button"  defaultSortColumn="" columns={columnForPopup} summaryFilter={props.summaryFilter} selectedRange={selectedRange} searchText={searchTextOnly} empId={applicationDetails.emp_code} applicationName={applicationDetails.application_name} togglePopup={togglePopup} />
          </div>
        )
      }
      <CommonTable data={data} cols={cols} data-testid="common-table" columns={columns} defaultSortColumn="" onChange={getData} filters={filter} togglePopup={togglePopup} />
      {loading && <Loader />}
    </div>
  </div>
}


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

export default RunningApplicationDetails;
