import "../pages/ManageUsers.css";
import { Button, Checkbox } from "@mui/material";
import React, { useState } from "react";
import PropTypes from "prop-types";
import Loader from "./Loader.js";


function PopupForFilter({ onClose, getUsersTable, filter, handleFilter, allRoles }) {
  const [checkboxValues, setCheckboxValues] = useState(filter.selectedValues || {});
  const [loading, setLoading] = useState(false);

  const onClear = () => {
    setCheckboxValues({});
    handleFilter(filter, true);
  };
  const handleCheckboxChange = ({ target: { name, checked } }) => {
    const updatedValues = { ...checkboxValues, [name]: checked };
    const newFilter = buildFilter(updatedValues);
    setCheckboxValues(updatedValues);
    const updatedFilter = {
      ...newFilter,
      selectedValues: updatedValues
    };
    handleFilter(updatedFilter, false);
  };
  const buildFilter = (values) => {
    const filters = [
      {
        check: ["active", "deactive", "deleted"],
        column: "user_status_name",
        map: { active: "Active", deactive: "Deactive", deleted: "Deleted" }
      },
      {
        check: allRoles.map(role => role.RoleName),
        column: "user_role_name",
        map: Object.fromEntries(allRoles.map(role => [role.RoleName, role.RoleName]))
      }
    ];

    const columns = [];
    const valuesArr = [];

    filters.forEach(({ check, column, map }) => {
      const filteredValues = check.filter(key => values[key]);
      if (filteredValues?.length) {
        columns.push(column);
        valuesArr.push(...filteredValues.map(key => map[key]));
      }
    });

    return {
      ...filter,
      Filter: {
        ...filter.Filter,
        FilterColumn: columns,
        FilterValue: valuesArr,
      }
    };
  };

  const handleFilters = async () => {
    setLoading(true);
    try {
      getUsersTable(filter);
    } catch (err) {
      console.error("Error fetching filtered data", err);
    } finally {
      setLoading(false);
      onClose();
    }
  };

  const renderCheckboxGroup = (label, options) => (
    <>      <h4 style={{ margin: "10px 0", color: "#252323", fontWeight: "bold", borderBottom: "1px solid #ccc", textTransform: "capitalize" }}>
      {label}
    </h4>
      <div style={{ padding: "10px 0" }} className={label === "Roles" ? 'add-scroller' : 'no-scroller'}>
        {options.map(({ label, name }) => (
          <div key={name} className="label-font">
            <Checkbox
              name={name}
              checked={checkboxValues[name] || false}
              onChange={handleCheckboxChange}
              size="small"
            />
            {label}
          </div>
        ))}
      </div>
    </>

  );

  return (
    <div>
      <div className="popupFilter-content" style={{ padding: "10px", background: "#f8f8f8", borderRadius: "10px", height: "auto" }}>
        <div className="d-flex headingpop">
          <h3>Filters</h3>
          <Button onClick={onClear} style={{ background: "transparent", color: "blue", marginLeft: "auto" }}>
            CLEAR ALL
          </Button>
        </div>

        {renderCheckboxGroup("Status", [
          { label: "Active", name: "active" },
          { label: "Deactive", name: "deactive" },
          { label: "Deleted", name: "deleted" },
        ])}

        {renderCheckboxGroup("Roles", allRoles.map(role => ({
          label: role.RoleName,
          name: role.RoleName
        })))}

        <div className="buttons" style={{ display: "flex", justifyContent: "flex-end", gap: "10px", margin: "10px 0" }}>
          <Button variant="outlined" onClick={onClose}>Cancel</Button>
          <Button variant="contained" onClick={handleFilters}>Apply Filters</Button>
          {loading && <Loader />}
        </div>
      </div>
    </div>
  );
}

PopupForFilter.propTypes = {
  onClose: PropTypes.func.isRequired,
  getUsersTable: PropTypes.func.isRequired,
  handleFilter: PropTypes.func.isRequired,
  filter: PropTypes.shape({
    selectedValues: PropTypes.object,
    Filter: PropTypes.shape({
      FilterColumn: PropTypes.array,
      FilterValue: PropTypes.array,
    })
  }),
  allRoles: PropTypes.arrayOf(
    PropTypes.shape({
      RoleName: PropTypes.string.isRequired
    })
  )
};


PopupForFilter.defaultProps = {
  filter: {
    selectedValues: {},
    Filter: {
      FilterColumn: [],
      FilterValue: [],
    }
  },
  allRoles: []
};


export default PopupForFilter;
