import React, { useState, useEffect } from "react";

const FilterIcon = ({
  taskListData,
  onApplyFilters,
  currentSelectedBuilding,
  currentSelectedFloors,
  currentSelectedActivities,
}) => {
  const [selectedBuilding, setSelectedBuilding] = useState(currentSelectedBuilding || "");
  const [selectedFloors, setSelectedFloors] = useState(currentSelectedFloors || []);
  const [selectedActivities, setSelectedActivities] = useState(currentSelectedActivities || []);

  useEffect(() => {
    setSelectedBuilding(currentSelectedBuilding || "");
    setSelectedFloors(currentSelectedFloors || []);
    setSelectedActivities(currentSelectedActivities || []);
  }, [currentSelectedBuilding, currentSelectedFloors, currentSelectedActivities]);

  const getUniqueFilterValues = (key, overrideBuilding, overrideFloors) => {
    if (!taskListData) return [];

    let filteredTasks = [...taskListData];

    if (overrideBuilding) {
      filteredTasks = filteredTasks.filter(
        (task) =>
          task?.workItem?.workArea?.floor?.building?.name === overrideBuilding
      );
    }

    if (overrideFloors?.length > 0) {
      filteredTasks = filteredTasks.filter((task) =>
        overrideFloors.includes(task?.workItem?.workArea?.floor?.floorName)
      );
    }

    const values = filteredTasks.map((task) => {
      if (key === "building") return task?.workItem?.workArea?.floor?.building?.name;
      if (key === "floor") return task?.workItem?.workArea?.floor?.floorName;
      if (key === "activity") return task?.workItem?.activityMaster?.activityName;
      return null;
    });

    return [...new Set(values.filter(Boolean))].sort();
  };

  const uniqueBuildings = getUniqueFilterValues("building");
  const uniqueFloors = getUniqueFilterValues("floor", selectedBuilding);
  const uniqueActivities = getUniqueFilterValues("activity", selectedBuilding, selectedFloors);

  const handleFilterChange = (filterType, value) => {
    let updatedBuilding = selectedBuilding;
    let updatedFloors = [...selectedFloors];
    let updatedActivities = [...selectedActivities];

    if (filterType === "building") {
      updatedBuilding = value;
      updatedFloors = [];
      updatedActivities = [];
    } else if (filterType === "floor") {
      if (updatedFloors.includes(value)) {
        updatedFloors = updatedFloors.filter((floor) => floor !== value);
      } else {
        updatedFloors.push(value);
      }

      const validActivities = getUniqueFilterValues("activity", updatedBuilding, updatedFloors);
      updatedActivities = updatedActivities.filter((act) => validActivities.includes(act));
    } else if (filterType === "activity") {
      if (updatedActivities.includes(value)) {
        updatedActivities = updatedActivities.filter((act) => act !== value);
      } else {
        updatedActivities.push(value);
      }
    }

    setSelectedBuilding(updatedBuilding);
    setSelectedFloors(updatedFloors);
    setSelectedActivities(updatedActivities);

    onApplyFilters({
      selectedBuilding: updatedBuilding,
      selectedFloors: updatedFloors,
      selectedActivities: updatedActivities,
    });
  };

  const clearAllFilters = () => {
    setSelectedBuilding("");
    setSelectedFloors([]);
    setSelectedActivities([]);

    onApplyFilters({
      selectedBuilding: "",
      selectedFloors: [],
      selectedActivities: [],
    });
  };

  return (
    <div className="dropdown">
      <a
        className="dropdown-toggle hide-arrow cursor-pointer"
        id="filterDropdown"
        data-bs-toggle="dropdown"
        aria-expanded="false"
      >
        <i
          className="fa-solid fa-filter bx-sm"
          style={{ color: selectedBuilding || selectedFloors.length > 0 || selectedActivities.length > 0 ? "#7161EF" : "gray" }}
        ></i>

      </a>
      <ul
        className="dropdown-menu p-2"
        aria-labelledby="filterDropdown"
        style={{ minWidth: "360px", fontSize: "13px" }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Building */}
        <li>
          <div className="fw-bold text-dark mb-1">Building</div>
          <div className="row">
            <div className="col-12">
              <select
                className="form-select form-select-sm"
                value={selectedBuilding}
                onChange={(e) => handleFilterChange("building", e.target.value)}
              >
                <option value="">Select Building</option>
                {uniqueBuildings.map((building, idx) => (
                  <option key={idx} value={building}>
                    {building}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </li>

        {/* Floor */}
        {selectedBuilding && (
          <>
            <li><hr className="my-1" /></li>
            <li>
              <div className="fw-bold text-dark mb-1">Floors</div>
              <div className="row">
                {uniqueFloors.length > 0 ? (
                  uniqueFloors.map((floor, idx) => (
                    <div className="col-6" key={idx}>
                      <div className="form-check mb-1">
                        <input
                          className="form-check-input"
                          type="checkbox"
                          id={`floor-${floor}`}
                          checked={selectedFloors.includes(floor)}
                          onChange={() => handleFilterChange("floor", floor)}
                        />
                        <label className="form-check-label" htmlFor={`floor-${floor}`}>
                          {floor}
                        </label>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="col-12 text-muted">No floors found.</div>
                )}
              </div>
            </li>
          </>
        )}

        {/* Activity */}
        {selectedFloors.length > 0 && (
          <>
            <li><hr className="my-1" /></li>
            <li>
              <div className="fw-bold text-dark mb-1">Activities</div>
              <div className="row">
                {uniqueActivities.length > 0 ? (
                  uniqueActivities.map((activity, idx) => (
                    <div className="col-6" key={idx}>
                      <div className="form-check mb-1">
                        <input
                          className="form-check-input"
                          type="checkbox"
                          id={`activity-${activity}`}
                          checked={selectedActivities.includes(activity)}
                          onChange={() => handleFilterChange("activity", activity)}
                        />
                        <label className="form-check-label" htmlFor={`activity-${activity}`}>
                          {activity}
                        </label>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="col-12 text-muted">No activities found.</div>
                )}
              </div>
            </li>
          </>
        )}

        {/* Action Buttons */}
        <li><hr className="my-1" /></li>
        {(selectedBuilding || selectedFloors.length > 0 || selectedActivities.length > 0) && (
          <li className="d-flex justify-content-end gap-2 px-2">
            <button
              type="button"
              className="btn btn-sm"
              style={{
                backgroundColor: "#7161EF",
                color: "white",
                fontSize: "13px",
                padding: "4px 16px",
                borderRadius: "8px",
                boxShadow: "0 1px 4px rgba(0,0,0,0.1)"
              }}
              onClick={clearAllFilters}
            >
              Clear
            </button>
            <button
              type="button"
              className="btn btn-sm"
              style={{
                backgroundColor: "#7161EF",
                color: "white",
                fontSize: "13px",
                padding: "4px 16px",
                borderRadius: "8px",
                boxShadow: "0 1px 4px rgba(0,0,0,0.1)"
              }}
              onClick={() => {
                document.getElementById("filterDropdown").click();
              }}
            >
              Apply
            </button>
          </li>
        )}


      </ul>
    </div>
  );
};

export default FilterIcon;
