import React, { useEffect, useState, useCallback, useRef } from "react";
import PropTypes from "prop-types";
import CommonTable from "../../components/CommonTable.js";
import { callDetailsApi } 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 Loader from "../../components/Loader.js";
import { commonFilterActivityLogs } from "../../constants/defaultFilters.js";
import "../Dashboard.css";

function CallDetails({
  employeeId,
  EmployeeName,
  title,
  summaryFilter,
  filter: externalFilter,
}) {
  const { postApi } = useApiService();

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [searchTextOnly, setSearchTextOnly] = useState("");
  const initialRange = getTodayDateRange();

  const [filter, setFilter] = useState({
    ...commonFilterActivityLogs,
    SearchText: employeeId || null,
    Filter: {
      CallStartedOn: summaryFilter?.CallDate?.startDate || initialRange.startDate,
      CallEndedOn: summaryFilter?.CallDate?.endDate || initialRange.endDate,
      ResultsFor: summaryFilter?.ResultsFor || null,
    },
  });



  const getData = useCallback(async (updatedFilter) => {
    setLoading(true);
    try {
      const updatedFilterData = { ...filter, ...updatedFilter };
      setFilter(updatedFilterData);

      const result = await postApi(callDetailsApi, updatedFilterData);
      // API returns a paginated object: { Records, TotalRecords, CurrentPage, ... }
      // Pass it through as-is so CommonTable can read data.Records, etc.
      setData(result || []);
    } catch (error) {
      console.error("Error fetching call details:", error);
    } finally {
      setLoading(false);
    }
  }, [filter, postApi]);

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

  // Only fetch data when externalFilter actually changes, not on every render
  useEffect(() => {
    if (!hasInitialized.current) {
      hasInitialized.current = true;
      if (externalFilter) {
        getData(externalFilter);
      } else {
        getData({});
      }
    }
  }, [getData, externalFilter]);


  const handleDateFilterChange = (filterType, dateRange) => {
    const empCode =
      searchTextOnly ||
      EmployeeName ||
      summaryFilter?.EmpCode ||
      null;

    const updatedFilter = {
      ...filter,
      SearchText: empCode,
      PageSize: 50,
      PageNumber: 1,
      IgnorePaging: false,
      Filter: {
        ...filter.Filter,
        CallStartedOn: dateRange?.startDate,
        CallEndedOn: dateRange?.endDate,
        EmpCode: empCode,
      },
    };

    getData(updatedFilter);
  };

  const handleSearch = (searchText) => {
    setSearchTextOnly(searchText);

    const updatedFilters = {
      ...filter,
      SearchText: searchText.toLowerCase(),
    };

    getData(updatedFilters);
  };



  const cols = {
    field: "EmpCode",
    headerName: "Employee",
    type: String,
  };

  useEffect(() => {
    if (title === "userProfile") {
      setColumns([
        {
          field: "Total_Call_Duration",
          headerName: "Total Call Duration",
          type: Number,
          flex: 2,
        },
        { field: "CallWith", headerName: "Call With", type: String, flex: 3 },
        {
          field: "CallStartedOn",
          headerName: "Started On",
          type: Date,
          flex: 2,
        },
        { field: "CallEndedOn", headerName: "Ended On", type: Date, flex: 2 },
      ]);
    } else {
      setColumns([
        {
          field: "EmployeeName",
          headerName: "Employee",
          type: String,
          flex: 3,
        },
        {
          field: "Total_Call_Duration",
          headerName: "Total Call Duration",
          type: Number,
          flex: 2,
        },
        { field: "CallWith", headerName: "Call With", type: String, flex: 3 },
        {
          field: "CallStartedOn",
          headerName: "Started On",
          type: Date,
          flex: 2,
        },
        { field: "CallEndedOn", headerName: "Ended On", type: Date, flex: 2 },
      ]);
    }
  }, [title]);

  // =========================
  // UI
  // =========================

  return (
    <div className="inner-container">
      <div className="filters-wrapper">
        <DateFilterDropdown
          onChange={handleDateFilterChange}
          isRangePicker
        />

        <div className="other-filters">
          {!employeeId && <SearchInput onSearch={handleSearch} />}
        </div>
      </div>

      <div>
        <CommonTable
          title="callDetails"
          data={data}
          cols={cols}
          columns={columns}
          defaultSortColumn=""
          onChange={getData}
          filters={filter}
        />

        {loading && <Loader />}
      </div>
    </div>
  );
}

// =========================
// PropTypes
// =========================

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

export default CallDetails;