// src/components/filters/OwnerFilterDropdown.jsx
import React, { useMemo, useState } from "react";
import { HiOutlineUser } from "react-icons/hi2";
import { TbPaperclip } from "react-icons/tb";
import DropdownPortal from "./DropdownPortal";

export default function OwnerFilterDropdown({
  owners = [],
  selectedOwnerEmail,
  onOwnerChange,
  width = 320,
}) {
  const [menu, setMenu] = useState({ open: false, rect: null });
  const [search, setSearch] = useState("");
  const [activeAccessId, setActiveAccessId] = useState(null);
  const [openAccessRoleFor, setOpenAccessRoleFor] = useState(null);

  const accessRoleItems = [
    { value: "all", label: "همه" },
    { value: "owner", label: "مالک" },
    { value: "creator", label: "سازنده" },
    { value: "shared-by", label: "به اشتراک گذاشته شده توسط" },
    { value: "shared-with", label: "به اشتراک گذاشته شده با" },
  ];

  const filteredOwners = useMemo(
    () => owners.filter((email) => email.toLowerCase().includes(search.toLowerCase())),
    [owners, search]
  );

  const accessLabel = selectedOwnerEmail || "دسترسی";

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

  const toggle = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const rect = e.currentTarget.getBoundingClientRect();
    setMenu((p) => ({ open: !(p.open && p.rect), rect }));
    if (menu.open) {
      // اگر داشت بسته میشد
      setActiveAccessId(null);
      setOpenAccessRoleFor(null);
    }
  };

  const handleAccessClick = (email) => {
    setActiveAccessId(email);
    setOpenAccessRoleFor((prev) => (prev === email ? null : email));
    onOwnerChange?.(email);
  };

  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 border dark:border-white/10 border-neutral-200 dark:bg-[#A1E3F919] shadow 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"
      >
        <HiOutlineUser className="h-5 w-5 ml-1.5 dark:text-white text-[#43BEFF]" />
        <span className="ml-1.5">{accessLabel.length > 20 ? accessLabel.slice(0, 20) + "..." : accessLabel}</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}>
        {/* سرچ */}
        <div className="dark:bg-[#001F3F] bg-[#f2f2f2] border-b dark:border-white/10 border-[#A1E3F9] p-2 rounded-t-2xl">
          <input
            type="text"
            className="dark:bg-[#A1E3F919] bg-[#A1E3F980] dark:text-white text-black text-sm rounded-md block w-full px-2.5 py-2 shadow-xs dark:placeholder:text-white placeholder:text-black outline-0 ring-0"
            placeholder="جستجوی صاحب فایل"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>

        {/* لیست */}
        <ul className="h-48 p-2 text-sm dark:text-white text-black font-medium overflow-y-auto">
          {filteredOwners.map((email) => (
            <li
              key={email}
              className={`w-full flex items-center p-2 rounded-md relative cursor-pointer ${
                activeAccessId === email ? "dark:bg-[#A1E3F919] bg-[#A1E3F980]" : "dark:hover:bg-[#A1E3F919] hover:bg-[#A1E3F980]"
              }`}
              onClick={() => handleAccessClick(email)}
            >
              <div className="flex items-center justify-between w-full">
                <div className="inline-flex items-center font-medium">
                  <div className="w-6 h-6 ms-2 rounded-full dark:bg-[#A1E3F919] bg-[#A1E3F980] flex items-center justify-center text-[10px]">
                    {email[0]?.toUpperCase()}
                  </div>
                  <span className="me-2 truncate max-w-[150px]">{email}</span>
                </div>

                <svg className="w-4 h-4 dark:text-white text-black" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
                  <path d="M9 5L16 12L9 19" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>

              {/* ساب‌منو */}
              {openAccessRoleFor === email && (
                <div className="absolute top-0 left-full ml-2 w-56 dark:bg-[#001F3F] bg-[#f2f2f2] rounded-2xl shadow-lg p-2 z-20 border border-black/5 dark:border-white/10">
                  <div className="text-xs dark:text-white/70 text-black text-right mb-2">نوع دسترسی برای این کاربر</div>
                  <ul className="space-y-1">
                    {accessRoleItems.map((role) => (
                      <li key={role.value}>
                        <button
                          type="button"
                          className="w-full text-right text-xs dark:text-white text-black px-2 py-1.5 rounded-md dark:hover:bg-[#A1E3F919] hover:bg-[#A1E3F980]"
                          onClick={(e) => e.stopPropagation()}
                        >
                          {role.label}
                        </button>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </li>
          ))}
        </ul>

        <div className="dark:bg-[#001F3F] bg-[#f2f2f2] border-t dark:border-[#A1E3F919] border-[#A1E3F980] p-2 rounded-b-2xl">
          <button
            type="button"
            className="dark:text-white text-black text-right font-medium w-full text-sm px-1 py-2 flex gap-2 items-center rounded-md dark:hover:bg-[#A1E3F919] hover:bg-[#A1E3F980]"
          >
            <TbPaperclip className="h-4 w-4 dark:text-white text-[#43BEFF]" />
            هر کسی که لینک را دارد
          </button>
        </div>
      </DropdownPortal>
    </div>
  );
}
