import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { LuChevronDown, LuCheck } from "react-icons/lu";

function clamp(n, min, max) {
  return Math.max(min, Math.min(max, n));
}

export default function FilterDropdown({
  value,
  options = [], // [{value,label,disabled?}]
  onChange,
  placeholder = "انتخاب",
  buttonClassName = "",
  menuClassName = "",
  disabled = false,
  align = "right", // right | left
}) {
  const btnRef = useRef(null);
  const [open, setOpen] = useState(false);
  const [rect, setRect] = useState(null);

  const selected = useMemo(
    () => options.find((o) => String(o.value) === String(value)),
    [options, value]
  );

  const label = selected?.label || placeholder;

  const close = () => setOpen(false);

  const toggle = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (disabled) return;

    const r = btnRef.current?.getBoundingClientRect();
    setRect(r || null);
    setOpen((p) => !p);
  };

  // close on outside click + ESC
  useEffect(() => {
    if (!open) return;

    const onDown = (e) => {
      const target = e.target;
      // اگر روی خود دکمه کلیک شد، toggle خودش هندل می‌کنه
      if (btnRef.current && btnRef.current.contains(target)) return;
      close();
    };

    const onKey = (e) => {
      if (e.key === "Escape") close();
    };

    document.addEventListener("pointerdown", onDown, true);
    document.addEventListener("keydown", onKey, true);

    return () => {
      document.removeEventListener("pointerdown", onDown, true);
      document.removeEventListener("keydown", onKey, true);
    };
  }, [open]);

  // keep rect fresh on open (if layout shifts)
  useLayoutEffect(() => {
    if (!open) return;
    const r = btnRef.current?.getBoundingClientRect();
    setRect(r || null);
  }, [open]);

  const menu = useMemo(() => {
    if (!open || !rect) return null;

    const width = rect.width;
    const top = rect.bottom + 8;

    const left =
      align === "left"
        ? rect.left
        : rect.right - width;

    const vw = window.innerWidth;
    const vh = window.innerHeight;

    const finalLeft = clamp(left, 8, vw - width - 8);
    const maxH = clamp(vh - top - 12, 160, 360);

    return createPortal(
      <div
        style={{
          position: "fixed",
          top,
          left: finalLeft,
          width,
          zIndex: 99999,
        }}
        className="pointer-events-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div
          className={[
            "rounded-2xl shadow border border-black/10 dark:border-white/10",
            "bg-white dark:bg-[#16325b] overflow-hidden",
            menuClassName,
          ].join(" ")}
          style={{ maxHeight: maxH }}
        >
          <div className="max-h-full overflow-auto p-1">
            {options.map((opt) => {
              const isActive = String(opt.value) === String(value);
              const isDisabled = !!opt.disabled;

              return (
                <button
                  key={String(opt.value)}
                  type="button"
                  disabled={isDisabled}
                  onClick={() => {
                    if (isDisabled) return;
                    onChange?.(opt.value);
                    close();
                  }}
                  className={[
                    "w-full text-right px-3 py-2 rounded-xl transition flex items-center justify-between gap-2",
                    isDisabled ? "opacity-50 cursor-not-allowed" : "hover:bg-black/5 dark:hover:bg-white/10",
                    isActive ? "bg-[#43BEFF]/15" : "",
                  ].join(" ")}
                >
                  <span className="text-sm text-black dark:text-white">{opt.label}</span>
                  {isActive ? <LuCheck className="w-4 h-4 text-[#43BEFF]" /> : null}
                </button>
              );
            })}
          </div>
        </div>
      </div>,
      document.body
    );
  }, [open, rect, options, value, onChange, menuClassName, align]);

  return (
    <>
      <button
        ref={btnRef}
        type="button"
        onClick={toggle}
        disabled={disabled}
        className={[
          "h-11 px-3 rounded-xl shadow",
          "bg-[#A1E3F980] dark:bg-[#A1E3F919]",
          "border border-black/10 dark:border-white/10",
          "text-sm inline-flex items-center justify-between gap-2",
          "outline-0 transition disabled:opacity-60",
          buttonClassName,
        ].join(" ")}
        title={label}
      >
        <span className="truncate">{label}</span>
        <LuChevronDown className={`w-4 h-4 opacity-80 ${open ? "rotate-180" : ""} transition`} />
      </button>

      {menu}
    </>
  );
}
