import { type ChangeEvent, useMemo, useState } from "react";

import styles from "./styles.module.scss";

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

interface DropdownProps {
  options: Option[];
  onSelect: (option: Option) => void;
}

export default function Dropdown({ options, onSelect }: DropdownProps) {
  const [selectedOption, setSelectedOption] = useState<Option | null>(null);

  const sortedOptions = useMemo(() => {
    return [...options].sort((a, b) => a.label.localeCompare(b.label));
  }, [options]);

  const handleChange = (event: ChangeEvent<HTMLSelectElement>) => {
    const selected = sortedOptions.find(
      (option) => option.value === event.target.value,
    );
    setSelectedOption(selected || null);
    if (selected) {
      onSelect(selected);
    }
  };

  return (
    <div className={styles.dropdown}>
      <select onChange={handleChange} value={selectedOption?.value || ""}>
        <option value="">Filter</option>
        {sortedOptions.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    </div>
  );
}
