"use client";

import { useEffect, useRef, useState } from "react";
import { ChevronDown, Search, X } from "lucide-react";

interface CommunityMultiSelectProps {
  id: string;
  value: string[];
  options: { id: string | number; name: string }[];
  disabled?: boolean;
  onChange: (ids: string[]) => void;
}

export function CommunityMultiSelect({ id, value, options, disabled, onChange }: CommunityMultiSelectProps) {
  const [search, setSearch] = useState("");
  const dropdownRef = useRef<HTMLDetailsElement>(null);

  useEffect(() => {
    const closeOutside = (event: PointerEvent) => {
      const dropdown = dropdownRef.current;
      if (dropdown && event.target instanceof Node && !dropdown.contains(event.target)) {
        dropdown.open = false;
      }
    };
    document.addEventListener("pointerdown", closeOutside);
    return () => document.removeEventListener("pointerdown", closeOutside);
  }, []);

  useEffect(() => {
    if (disabled && dropdownRef.current) dropdownRef.current.open = false;
  }, [disabled]);
  const ids = options.map((option) => String(option.id));
  const allSelected = ids.length > 0 && ids.every((optionId) => value.includes(optionId));
  const filteredOptions = options.filter((option) => option.name.toLowerCase().includes(search.trim().toLowerCase()));

  return (
    <details ref={dropdownRef} id={id} className={`group relative text-sm ${disabled ? "pointer-events-none opacity-60" : ""}`} onToggle={(event) => {
      if (!event.currentTarget.open) setSearch("");
    }} onBlur={(event) => {
      if (!event.currentTarget.contains(event.relatedTarget)) event.currentTarget.open = false;
    }} onKeyDown={(event) => {
      if (event.key === "Escape") {
        event.currentTarget.open = false;
        event.currentTarget.querySelector("summary")?.focus();
      }
    }}>
      <summary aria-disabled={disabled} tabIndex={disabled ? -1 : 0} aria-label="Community" className="flex cursor-pointer list-none items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 px-4 py-2.5 text-gray-900 outline-none transition-colors focus-visible:border-blue-500 focus-visible:ring-2 focus-visible:ring-blue-100 group-open:border-blue-400 group-open:bg-white [&::-webkit-details-marker]:hidden">
        <span className="flex min-w-0 flex-1 flex-wrap gap-1.5">
          {!value.length && <span className="text-gray-400">Select communities</span>}
          {value.map((optionId) => {
            const name = options.find((option) => String(option.id) === optionId)?.name ?? "Selected community";
            return <span key={optionId} className="inline-flex max-w-full items-center gap-1 rounded-md border border-blue-100 bg-blue-50 py-1 pl-2 pr-1 text-xs font-medium text-blue-800">
              <span className="min-w-0 break-words [overflow-wrap:anywhere]">{name}</span>
              <button type="button" disabled={disabled} aria-label={`Remove ${name}`} onClick={(event) => {
                event.preventDefault();
                event.stopPropagation();
                onChange(value.filter((item) => item !== optionId));
              }} onKeyDown={(event) => event.stopPropagation()} className="shrink-0 rounded p-0.5 text-blue-600 hover:bg-blue-100 focus-visible:outline-2 focus-visible:outline-blue-500">
                <X aria-hidden="true" className="h-3.5 w-3.5" />
              </button>
            </span>;
          })}
        </span>
        <ChevronDown className="h-4 w-4 shrink-0 text-gray-400 transition-transform group-open:rotate-180" />
      </summary>
      {!disabled && <div className="absolute inset-x-0 top-full z-20 mt-1.5 overflow-hidden rounded-xl border border-gray-200 bg-white shadow-lg shadow-gray-200/60">
        <div className="border-b border-gray-100 p-3">
          <div className="relative">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <input type="search" aria-label="Search communities" value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Search communities..." className="w-full rounded-lg border border-gray-200 bg-gray-50 py-2 pl-9 pr-3 text-sm outline-none focus:border-blue-500 focus:bg-white focus:ring-1 focus:ring-blue-500" />
          </div>
          <div className="mt-3 flex items-center justify-between">
            <label className="flex cursor-pointer items-center gap-2 text-sm font-medium text-gray-700">
              <input type="checkbox" checked={allSelected} disabled={!ids.length} onChange={() => onChange(allSelected ? [] : ids)} className="h-4 w-4 rounded border-gray-300 accent-blue-600" />Select All
            </label>
            <span className="text-xs text-gray-400">{value.length} of {options.length} selected</span>
          </div>
        </div>
        <div className="max-h-44 space-y-1 overflow-y-auto p-2">
          {filteredOptions.map((option) => {
            const optionId = String(option.id);
            const selected = value.includes(optionId);
            return <label key={optionId} className={`flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 transition-colors ${selected ? "bg-blue-50 text-blue-800" : "text-gray-700 hover:bg-gray-50"}`}>
              <input type="checkbox" checked={selected} onChange={() => onChange(selected ? value.filter((item) => item !== optionId) : [...value, optionId])} className="h-4 w-4 shrink-0 rounded border-gray-300 accent-blue-600" />
              <span className="min-w-0 break-words leading-5">{option.name}</span>
            </label>;
          })}
          {!filteredOptions.length && <p className="px-3 py-5 text-center text-sm text-gray-400">{options.length ? "No matching communities." : "No communities available."}</p>}
        </div>
      </div>}
    </details>
  );
}
