import React, { useEffect, useState } from "react";
import Search from "../../components/ui/inputs/Search";
import { StarsIcon } from "../../components/icons/marketPlaceIcons";
import RegularDropDown from "../../components/ui/inputs/RegularDropDown";

interface ModelData {
  CreatedBy: string;
  animated: string | null;
  category: string;
  description: string;
  filename: string;
  isArchieve: boolean;
  assetId: string;
  tags: string;
  thumbnail: string;
  uploadDate: number;
  _id: string;
  price: number;
  AssetID: string;
}

interface ModelsProps {
  models: ModelData[];
  setModels: React.Dispatch<React.SetStateAction<ModelData[]>>;
  filteredModels: ModelData[];
}

const FilterSearch: React.FC<ModelsProps> = ({
  models,
  setModels,
  filteredModels,
}) => {
  const [activeOption, setActiveOption] = useState("Sort by");
  const [rating, setRating] = useState(0);

  const handleSelect = (option: string) => {
    setActiveOption(option);
  };

  useEffect(() => {
    if (activeOption === "Alphabet ascending") {
      const ascending = [...models].sort((a, b) =>
        a.filename.localeCompare(b.filename)
      );
      setModels(ascending);
    } else if (activeOption === "Alphabet descending") {
      const descending = [...models].sort((a, b) =>
        b.filename.localeCompare(a.filename)
      );
      setModels(descending);
    }
  }, [activeOption, models, setModels]);

  const handleSearch = (val: string) => {
    const filteredModel = filteredModels.filter((model) =>
      model.filename.toLowerCase().includes(val.toLowerCase())
    );
    setModels(filteredModel);
  };

  const handleStarClick = (index: number) => {
    setRating(index + 1);
  };

  return (
    <div className="filter-search-container">
      <Search onChange={handleSearch} />
      <RegularDropDown
        header={activeOption}
        options={["Alphabet ascending", "Alphabet descending", ""]}
        onSelect={handleSelect}
        search={false}
      />
      <div className="button">Free</div>
      <div className="button">Animated</div>

      <div className="rating-container">
        <div className="label">Rating</div>
        <div className="stars">
          {[0, 1, 2, 3, 4].map((i) => (
            <button
              id={`${i + 1}-star-button`}
              key={i}
              onClick={() => handleStarClick(i)}
              className={`star-wrapper ${i < rating ? "filled" : "empty"}`}
            >
              <StarsIcon />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

export default FilterSearch;
