"use client";

import React, { useState, useRef, useEffect } from "react";

import "./custom-dropdown.css";

export interface CustomDropdownOption {
  value: string;
  label: string;
}

interface CustomDropdownProps {
  value: string;
  options: CustomDropdownOption[];
  onChange: (name: string, value: string) => void;
  name: string;
  placeholder?: string;
  /** Extra class for the wrapper */
  className?: string;
  /** Smaller trigger text (e.g. for inline filters) */
  isMinimal?: boolean;
  /** Visual variant for list (default: white, search: grey, advance: light grey) */
  variant?: "default" | "search" | "advance";
  /** aria-label for accessibility */
  "aria-label"?: string;
}

/** Custom div-based dropdown: trigger + list, click-outside to close. No deps, SSR-safe. */
const CustomDropdown: React.FC<CustomDropdownProps> = ({
  value,
  options,
  onChange,
  name,
  placeholder = "All",
  className = "",
  isMinimal = false,
  variant = "default",
  "aria-label": ariaLabel,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const selectedOption = options.find((o) => o.value === value);
  const displayText = selectedOption ? selectedOption.label : placeholder;

  useEffect(() => {
    if (!isOpen) return;
    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [isOpen]);

  const handleSelect = (opt: CustomDropdownOption) => {
    onChange(name, opt.value);
    setIsOpen(false);
  };

  return (
    <div
      ref={containerRef}
      className={`custom-dropdown custom-dropdown--${variant} ${className}`}
      data-minimal={isMinimal ? "" : undefined}
    >
      <button
        type="button"
        className="custom-dropdown__trigger"
        onClick={() => setIsOpen((prev) => !prev)}
        aria-expanded={isOpen}
        aria-haspopup="listbox"
        aria-label={ariaLabel ?? name}
      >
        <span className="custom-dropdown__value">{displayText}</span>
        <span className="custom-dropdown__chevron" aria-hidden>
          <ChevronDown />
        </span>
      </button>

      {isOpen && (
        <div
          className="custom-dropdown__list"
          role="listbox"
          onWheel={(e) => e.stopPropagation()}
        >
          {options.map((opt) => (
            <div
              key={opt.value}
              role="option"
              aria-selected={opt.value === value}
              className={`custom-dropdown__option ${opt.value === value ? "custom-dropdown__option--selected" : ""}`}
              onClick={() => handleSelect(opt)}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  handleSelect(opt);
                }
              }}
              tabIndex={0}
            >
              {opt.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

function ChevronDown() {
  return (
    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden>
      <path d="M6 8L1 3h10z" fill="currentColor" />
    </svg>
  );
}

export default CustomDropdown;
