import React, { useEffect, useState, useCallback } from 'react'
import { useLocation } from "react-router-dom";
import { Grid } from '@mui/material';
import CommonTable from '../components/CommonTable.js';
import { UsersApi } from "../constants/apiEndPoints.js";
import SearchInput from '../components/SearchInput.js';
import DropdownMenu from '../utils/Dropdown.js';
import useApiService from "../services/apiService.js"
import Loader from '../components/Loader.js';
import DateFilterDropdown from '../components/DateFilterDropdown.js';
import { getTodayDateRange } from '../constants/dateUtils.js';
import "../pages/Users.css";

import { userListStatusFilter } from '../constants/userConstants.js';

function Users() {
  const { postApi } = useApiService()
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [searchText, setSearchText] = useState("")
  const location = useLocation();
  const source = location.state?.from || "unknown";
  const [listFilter, setListFilter] = useState(source === "button" ? userListStatusFilter[1].value : userListStatusFilter[0].value)
  const initialDateRange = getTodayDateRange();
  const [filter, setFilter] = useState(
    {
      "SearchText":  searchText || "",
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "RequestDateStart": initialDateRange.startDate,
        "RequestDateEnd": initialDateRange.endDate,
        "SortOrder": "",
        "SortColumn": "",
        "ActiveUsers": source === "button"
      },
      "SortOrder": "DESC",
      "SortColumn": ""
    }
  )

  const getData = useCallback(async (updatedFilter) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...updatedFilter };
      setFilter(updatedFilterData);
      const result = await postApi(UsersApi, updatedFilterData);
      setData(result || []);
    } catch (error) {
      console.error("Error fetching data:", error);
      throw error; 
    } finally {
      setLoading(false);
    }
  }, [filter, postApi]);

  const handleSearch = (searchText) => {
    setSearchText(searchText);
    const updatedFilters = { ...filter, SearchText: searchText?.toLowerCase() };
    getData(updatedFilters);
  }

  const handleDateFilterChange = (filterType, dateRange) => {
    const updatedFilter = {
      "SearchText": searchText || "",
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "RequestDateStart": dateRange?.startDate || dateRange,
        "RequestDateEnd": dateRange?.endDate || dateRange,
        "SortOrder": "",
        "SortColumn": "",
        "ActiveUsers": source === "button"
      },
      "SortOrder": "DESC",
      "SortColumn": ""
    };
    getData(updatedFilter);
  };

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

  const handleClear = () => {
    setSearchText("");
    const updatedFilter = {
      "SearchText": "",
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": false,
      "Filter": {
        "RequestDateStart": null,
        "RequestDateEnd": null,
        "SortOrder": "",
        "SortColumn": "",
        "ActiveUsers": source === "button"
      },
      "SortOrder": "DESC",
      "SortColumn": ""
    }
    getData(updatedFilter);
  }

  const columns = [
    { field: 'EmpCode', headerName: 'Employee ID', type: String, width: 100, flex: 2 },
    { field: 'EmployeeName', headerName: 'Employee', type: String, width: 100, flex: 2 },
    { field: 'Department', headerName: 'Department', type: String, width: 200, flex: 2 },
    { field: 'TotalActive', headerName: 'Total Active', type: Number, width: 200, flex: 2 },
    { field: 'TotalIdle', headerName: 'Total Idle', type: Number, width: 200, flex: 2 },
    { field: 'TotalSleep', headerName: 'Total Sleep', type: Number, width: 200, flex: 2 },
    { field: 'Location', headerName: 'Location', type: String, width: 250, flex: 2 },

  ];

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

  const handleListFilter = (e) => {
    const {value} = e.target
    setListFilter(value)
    getData({ ...filter, Filter: { ...filter.Filter, ActiveUsers: value === "Active Users" } })
  }

  return <div className="outer-body">
    <div className='filters-wrapper filter-wrapper-user'>
      <div className="userList">
        <DateFilterDropdown
          onChange={handleDateFilterChange}
          initialFilter="Today"
          isRangePicker={true}
          placeholder="Select Date Range"
        />
      </div>
      <div className='other-filters'>
        <SearchInput onSearch={handleSearch} onClear={handleClear} />
        <div>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} sm="auto">
              <DropdownMenu
                value={listFilter}
                onSelectChange={(value) =>
                  handleListFilter({ target: { value } })
                }
                dropDownData={userListStatusFilter.map((item) => ({
                  Id: item.key,
                  Name: item.value
                }))}
                dropDownKeys={{ key: "Id", title: "Status" }}
              />
            </Grid>
          </Grid>

        </div>
      </div>
    </div>
    <div>
      <CommonTable cols={cols} data={data} columns={columns} defaultSortColumn="" onChange={getData} filters={filter} />
      {loading && <Loader />}
    </div>
  </div>
}

export default Users;
