import * as React from "react";
import Link from "next/link";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "../../../components/ui/Dropdown/dropdown-menu";

interface Item {
  href: string;
  label: string;
}

interface DropDownMenuProps {
  open: boolean;
  onOpenChange: React.Dispatch<React.SetStateAction<boolean>>;
  items: Item[];
  search: boolean;
  ITEMS_TO_DISPLAY?: number;
  icon: React.ReactNode;
  className?: string;
}

const DropDownMenu: React.FC<DropDownMenuProps> = ({
  open,
  onOpenChange,
  items,
  search,
  ITEMS_TO_DISPLAY = 0,
  icon,
  className,
}) => {
  const handleItemClick1 = (index: number) => {
    onOpenChange(false);
    console.log(index);
  };

  let from = 0;
  if (ITEMS_TO_DISPLAY) {
    from = 1;
  }
  const [searchQuery, setSearchQuery] = React.useState("");
  const filteredItems = items
    .slice(from, 1 + items.length - ITEMS_TO_DISPLAY)
    .filter((item) =>
      item.label.toLowerCase().includes(searchQuery.toLowerCase())
    );

  return (
    <DropdownMenu open={open} onOpenChange={onOpenChange}>
      <DropdownMenuTrigger
        className="flex items-center gap-1"
        aria-label="Toggle menu"
      >
        {icon}
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start">
        {search && (
          <input
            type="text"
            placeholder="Search..."
            className="w-full p-1 mb-2 border border-gray-300 rounded"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        )}
        {filteredItems.slice(0, items.length).map((item, index) => (
          <DropdownMenuItem
            key={index}
            onClick={() => handleItemClick1(index)}
            className={`max-w-20 truncate md:max-w-none`}
          >
            <Link href={item.href ? item.href : "#"}>{item.label}</Link>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
};

export default DropDownMenu;
