// src/components/filters/Dropdown.jsx
import React, { useMemo, useState } from "react";
import DropdownPortal from "./DropdownPortal";
import CustomDateRangeItem from "./CustomDateRangeItem";

export default function Dropdown({
  id,
  label,
  items,
  icon,
  selectedValue,
  onSelect,
  width = 260,
}) {
  const [menu, setMenu] = useState({ open: false, rect: null });

  const selectedItem = useMemo(() => items.find((i) => i.value === selectedValue), [items, selectedValue]);
  const displayLabel = selectedItem?.label || label;

  const close = () => setMenu({ open: false, rect: null });

  const toggle = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const rect = e.currentTarget.getBoundingClientRect();
    setMenu((p) => ({ open: !(p.open && p.rect), rect }));
  };

  return (
    <div className="relative sm:w-fit w-full inline-block">
      <button
        type="button"
        onClick={toggle}
        className="inline-flex items-center sm:justify-center justify-between sm:w-fit w-full shadow border dark:border-white/10 border-neutral-200 dark:bg-[#A1E3F919] dark:text-white text-black bg-brand box-border rounded-xl dark:shadow-xs font-medium leading-5 text-xs sm:text-sm md:text-md px-4 py-2.5"
      >
        {icon}
        <span className="ml-1.5">{displayLabel}</span>
        <svg
          className={`w-4 h-4 ms-1.5 dark:text-white text-[#43BEFF] -me-0.5 transition-transform duration-200 ${menu.open ? "rotate-180" : ""}`}
          aria-hidden="true"
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          fill="none"
          viewBox="0 0 24 24"
        >
          <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="m19 9-7 7-7-7" />
        </svg>
      </button>

      <DropdownPortal open={menu.open} rect={menu.rect} onClose={close} width={width}>
        <ul className="py-1.5 max-h-72 overflow-y-auto">
          {items.map((item) => {
            const isActive = selectedValue === item.value;

            return (
              <li key={item.value} className="px-1.5 p-0.5">
                {item.isCustom ? (
                  <CustomDateRangeItem
                    item={item}
                    isActive={isActive}
                    onApply={({ from, to }) => {
                      onSelect?.(item.value, { from, to });
                      close();
                    }}
                    onClear={() => {
                      onSelect?.(null);
                      close();
                    }}
                  />
                ) : (
                  <button
                    type="button"
                    className={`dark:text-white text-right w-full text-sm px-1 py-2 flex gap-2 items-center rounded-md ${
                      isActive ? "dark:bg-[#A1E3F919] bg-[#A1E3F980]" : "dark:hover:bg-[#A1E3F919] hover:bg-[#A1E3F980]"
                    }`}
                    onClick={() => {
                      onSelect?.(item.value);
                      close();
                    }}
                  >
                    {item.icon}
                    {item.label}
                  </button>
                )}
              </li>
            );
          })}
        </ul>
      </DropdownPortal>
    </div>
  );
}
