import { useState, useRef, useEffect } from 'react';
import './SortDropdown.css';

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

interface SortDropdownProps {
  options: SortOption[];
  value: string;
  order: 'asc' | 'desc';
  onChange: (value: string, order: 'asc' | 'desc') => void;
  className?: string;
}

export function SortDropdown({ options, value, order, onChange, className = '' }: SortDropdownProps) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const selectedOption = options.find((o) => o.value === value) || options[0];

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const toggleOrder = () => {
    onChange(value, order === 'asc' ? 'desc' : 'asc');
  };

  return (
    <div className={`sort-dropdown ${className}`.trim()} ref={dropdownRef}>
      <button
        type="button"
        className="sort-dropdown__trigger"
        onClick={() => setIsOpen(!isOpen)}
        aria-expanded={isOpen}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <line x1="4" y1="6" x2="20" y2="6" />
          <line x1="4" y1="12" x2="14" y2="12" />
          <line x1="4" y1="18" x2="8" y2="18" />
        </svg>
        <span>Sort: {selectedOption.label}</span>
        <svg
          className={`sort-dropdown__chevron ${isOpen ? 'sort-dropdown__chevron--open' : ''}`}
          width="14"
          height="14"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      <button
        type="button"
        className="sort-dropdown__order"
        onClick={toggleOrder}
        title={order === 'asc' ? 'Ascending' : 'Descending'}
      >
        {order === 'asc' ? (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <line x1="12" y1="19" x2="12" y2="5" />
            <polyline points="5 12 12 5 19 12" />
          </svg>
        ) : (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <line x1="12" y1="5" x2="12" y2="19" />
            <polyline points="19 12 12 19 5 12" />
          </svg>
        )}
      </button>

      {isOpen && (
        <div className="sort-dropdown__menu">
          {options.map((option) => (
            <button
              key={option.value}
              type="button"
              className={`sort-dropdown__option ${option.value === value ? 'sort-dropdown__option--selected' : ''}`}
              onClick={() => {
                onChange(option.value, order);
                setIsOpen(false);
              }}
            >
              {option.label}
              {option.value === value && (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
