/**
 * KRA - Dictionary Hook
 * Dictionary lookup and caching
 */
import { useState, useEffect, useCallback } from 'react';
import { useModel } from '@umijs/max';

interface DictItem {
  label: string;
  value: string | number;
  status?: string;
  tagType?: string;
}

export function useDictionary(type: string) {
  const [options, setOptions] = useState<DictItem[]>([]);
  const [loading, setLoading] = useState(false);

  // Try to use global dictionary model if available
  const { getDictionary } = useModel('dictionary', (model) => ({
    getDictionary: model?.getDictionary,
  })) || {};

  const fetchDictionary = useCallback(async () => {
    if (!type) return;
    
    setLoading(true);
    try {
      if (getDictionary) {
        const items = await getDictionary(type);
        setOptions(items || []);
      }
    } finally {
      setLoading(false);
    }
  }, [type, getDictionary]);

  useEffect(() => {
    fetchDictionary();
  }, [fetchDictionary]);

  // Get label by value
  const getLabel = useCallback(
    (value: string | number): string => {
      const item = options.find((opt) => opt.value === value);
      return item?.label || String(value);
    },
    [options]
  );

  // Get value by label
  const getValue = useCallback(
    (label: string): string | number | undefined => {
      const item = options.find((opt) => opt.label === label);
      return item?.value;
    },
    [options]
  );

  return {
    options,
    loading,
    getLabel,
    getValue,
    refresh: fetchDictionary,
  };
}

export default useDictionary;
