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 "./CommonTable.js";
import { userLocation } from "../constants/apiEndPoints.js";
import SearchInput from "./SearchInput.js";
import CustomDateRangePicker from "./DateRangePicker.js";
import useApiService from "../services/apiService.js"
import Loader from "./Loader.js";
import { getTodayDateRange } from '../constants/dateUtils.js';
import "../pages/Dashboard.css";


 function UserLocation(props) {
  const { postApi } = useApiService()
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [pickerVisible, setPickerVisible] = useState(false);
  const [searchTextOnly, setSearchTextOnly] = useState();
  const inputRef = useRef(null);
  const [selectedRange, setSelectedRange] = useState(getTodayDateRange());
  const [filter, setFilter] = useState({
    "SearchText": searchTextOnly || props.EmployeeName || props.summaryFilter.EmpCode,
    "PageSize": 10,
    "PageNumber": 1,
    "IgnorePaging": false,
    "Filter": {
      "EmpCode": props.summaryFilter.EmpCode || searchTextOnly|| props.EmployeeName,
      "UpdateOnStart": props.summaryFilter?.CallDate?.startDate || null,
      "UpdateOnEnd": props.summaryFilter?.CallDate?.endDate || null,
      "ResultsFor": props.summaryFilter?.ResultsFor || ""
    },
    "SortOrder": null,
    "SortColumn": null
  })

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

  const getData = async (updatedFilter) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...updatedFilter }
      setFilter(updatedFilterData)
      const result = await postApi(userLocation, updatedFilterData);
      setData(result || []);
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };
 
  const handleSelect = (date) => {
    setSelectedRange(date);
  };
  
  const applyDateRange = () => {
    if (inputRef.current) {
      inputRef.current.value = `${format(selectedRange.startDate, 'MM/dd/yyyy')} - ${format(selectedRange.endDate, 'MM/dd/yyyy')}`;
    }
    setPickerVisible(false);
    const updatedDateFilter = {
      "SearchText": searchTextOnly || props.EmployeeName || props.summaryFilter?.EmpCode ,
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "UpdateOnStart": selectedRange.startDate,
        "UpdateOnEnd": selectedRange.endDate,
        "Description": "",
      }
    }

    
    getData(updatedDateFilter)
  };

  const closeDateRangePicker = () => {
    setPickerVisible(false);
  };
 
  const handleInputClick = () => {
    setPickerVisible(!pickerVisible);
  };

  
  const handleSearch = (searchText) => {
    setSearchTextOnly(searchText)
    if (searchText?.length > 3 || searchText?.length == 0) {
      const updatedFilters = {
        ...filter,
        SearchText: searchText.toLowerCase(),
      };
      getData(updatedFilters);
    }

  };
  useEffect(() => {
   
      setColumns(
        [
          { field: 'Location', headerName: 'Location', type: String, flex: 3 },
          { field: 'latitude', headerName: 'Latitude', type: String, flex: 1 },  
          { field: 'longitude', headerName: 'Longitude', type: String, flex: 1 },
          { field: 'is_vpn_connected', headerName: 'Vpn Status', type: Boolean, flex: 1 },
          { field: 'updated_on', headerName: 'Updated on', type: Date, flex: 2 },
        ]);
    } 
     ,[props.title]);

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

  return <div className='inner-container'>
    <div className='filters-wrapper'>
      <div className="datepicker">
        <div className="date-picker-icon">
          <input
            ref={inputRef}
            type="text"
            placeholder="Select Date Range"
            onClick={handleInputClick}
            readOnly
            className="date-range-input calenderIcon"
          />
        </div>
        {pickerVisible && (
          <Box className="date-range-container" sx={{ boxShadow: 1, left: "2px" }}>
            <CustomDateRangePicker
              onChange={handleSelect}
              onApply={applyDateRange}
              onClose={closeDateRangePicker}
              selDate={selectedRange}
            />
          </Box>
        )}
      </div>
      <div className='other-filters'>
        {!props.employeeId && <SearchInput onSearch={handleSearch} onClear={getData} />}
      </div>
    </div>
    <div>
      <CommonTable data={data} cols={cols} columns={columns} defaultSortColumn="" onChange={getData} filters={filter} />
      
    </div>
    {loading && <Loader />}
  </div>
}

UserLocation.propTypes = {
  EmployeeName: 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,
  }),
  employeeId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  title: PropTypes.string
};

UserLocation.defaultProps = {
  EmployeeName: '',
  summaryFilter: {},
  employeeId: null,
  title: ''
};

export default UserLocation;
