import React, { useEffect, useState, useCallback, useRef } from 'react'
import CommonTable from '../../components/CommonTable.js';
import { getScreenshots } from "../../constants/apiEndPoints.js";
import SearchInput from '../../components/SearchInput.js';
import SingleDatePicker from '../../components/SingleDatePicker.js';
import useApiService from "../../services/apiService.js"
import Loader from '../../components/Loader.js';
import "../Dashboard.css";
import PropTypes from "prop-types";
import moment from 'moment';
import { toast } from 'react-toastify';

function Screenshots(props) {
  const { postApi } = useApiService()
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [searchTextOnly, setSearchTextOnly] = useState("")
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [filter, setFilter] = useState({
    "SearchText": "",
    "PageSize": 50,
    "PageNumber": 1,
    "IgnorePaging": true,
    "Filter": {
      Date: props.summaryFilter?.Date,
      EmployeeId: props.summaryFilter?.EmpCode || props.employeeId || null,
      ResultsFor: props.summaryFilter?.ResultsFor === "Select Results For" ? "" : props.summaryFilter?.ResultsFor,
    },
  })

  // Use useRef to prevent multiple initializations
  const hasInitialized = useRef(false);

  const getData = useCallback(async (updatedFilter) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...updatedFilter };
      setFilter(updatedFilterData);
      const result = await postApi(getScreenshots, updatedFilterData);
      setData(result || []);
    } catch (error) {
      console.error("Failed to fetch screenshots:", error);
      toast.error("Unable to load screenshots. Please try again later.");
      setData([]); // ✅ Prevent stale data from breaking the UI
    } finally {
      setLoading(false);
    }
  }, [filter, postApi]);

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

  const handleSingleDateChange = (dateValue) => {
    const newDate = new Date(dateValue);
    setSelectedDate(newDate);
    const formattedDate = moment(newDate).format("YYYY-MM-DD");
    const updatedDateFilter = {
      "Filter": {
        "EmployeeId": searchTextOnly || props.EmployeeName || props.summaryFilter?.EmpCode || null,
        "Date": formattedDate,
      },
      "PageNumber": 1,
      "PageSize": 50,
    };
    getData(updatedDateFilter);
  };


  const handleSearch = (searchText) => {
    setSearchTextOnly(searchText);
    const updatedFilters = {
      ...filter,
      SearchText: searchText.toLowerCase(),
      Filter: { ...filter.Filter, EmployeeId: Number.isNaN(searchText) ? null : searchText.toLowerCase() }
    };
    getData(updatedFilters);
  };

  const handleClear = (searchText) => {
    setSearchTextOnly("");
    const filter = {
      "SearchText": "",
      "PageSize": 50,
      "PageNumber": 1,
      "IgnorePaging": true,
      "Filter": {
        "EmployeeId": "",
        "Date": props.summaryFilter
      },
    }
    setFilter(filter);
    getData(filter);
  }


  useEffect(() => {
    if (props.title === "userProfile") {
      setColumns(
        [
          { field: 'NameApplication', headerName: 'Application', type: String, flex: 3 },
          { field: 'Date', headerName: 'Date', type: Date, flex: 2 },
          { field: 'Picture', headerName: 'Image', type: String, flex: 2, sortable: false },
        ]);
    } else {
      setColumns([
        { field: 'EmpCode', headerName: 'Employee', type: String, flex: 2 },
        { field: 'NameApplication', headerName: 'Application', type: String, flex: 3 },
        { field: 'Date', headerName: 'Date', type: Date, flex: 2 },
        { field: 'Picture', headerName: 'Image', type: String, flex: 2, sortable: false },
      ]);
    }
  }, [props.title]);



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

  return <div className='inner-container'>
    <div className='filters-wrapper'>
      <SingleDatePicker onChange={handleSingleDateChange} value={selectedDate} />
      <div className='other-filters'>
        {!props.employeeId && <SearchInput onSearch={handleSearch} onClear={handleClear} />}
      </div>
    </div>
    <div>
      <CommonTable data={data} cols={cols} disableSorting={false} enableRowNumbers columns={columns} defaultSortColumn="" onChange={getData} filters={filter} />
      {loading && <Loader />}
    </div>
  </div>
}

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

export default Screenshots;
