import { useEffect, useState, useMemo } from 'react';
import { listItemsByCode, type DictionaryItemInfo } from '../api/dictionaries';

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

export function useDictionary(code: string, fallback?: DictOption[]) {
  const [items, setItems] = useState<DictionaryItemInfo[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    listItemsByCode(code)
      .then((data) => setItems(data))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, [code]);

  const options = useMemo<DictOption[]>(() => {
    if (items.length > 0) {
      return items
        .sort((a, b) => a.sort_order - b.sort_order)
        .map((item) => ({ value: item.value, label: item.label }));
    }
    return fallback ?? [];
  }, [items, fallback]);

  return { items, options, loading };
}
