
import { useState, useEffect } from 'react';
import { optionsService } from '../services/optionsService';

export const useFleetOptions = () => {
  const [options, setOptions] = useState({});
  const [config, setConfig] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let mounted = true;

    const initOptions = async () => {
      try {
        setLoading(true);
        // 1. Fetch Config
        const configData = await optionsService.getConfig();
        
        if (mounted) {
            setConfig(configData);
        }

        // 2. Fetch All Lists derived from config
        // configData is expected to be { status_frota: { label: '...', rota: 'status_frota' }, ... }
        const allOptions = await optionsService.fetchAllLists(configData);
        
        if (mounted) {
            setOptions(allOptions);
        }
      } catch (err) {
        console.error("Failed to load fleet options", err);
        if (mounted) setError(err);
      } finally {
        if (mounted) setLoading(false);
      }
    };

    initOptions();

    return () => {
      mounted = false;
    };
  }, []);

  /**
   * Helper to safely get options for a key.
   * Returns an empty array if loading or not found.
   * Handles generic structure: if list items are strings, returns { value: item, label: item }
   * If they are objects, expects { id, nome } or similar, we might need normalization.
   * For now, we pass raw data.
   * 
   * @param {string} key - The route key from config (e.g., 'status_frota')
   */
  const getOptions = (key) => {
    return options[key] || [];
  };

  /**
   * Helper to normalize options for Select components.
   * Tries to map common fields to { value, label }.
   * @param {string} key 
   */
  const getSelectOptions = (key) => {
    const rawOptions = getOptions(key);
    if (!Array.isArray(rawOptions)) return [];

    return rawOptions.map(opt => {
        // If it's a simple string
        if (typeof opt === 'string') {
            return { value: opt, label: opt };
        }
        // If it's an object, try to guess
        // Adjust these contentions based on actual API response
        const value = opt.id || opt.value || opt.nome || opt.status || JSON.stringify(opt);
        const label = opt.nome || opt.label || opt.descricao || opt.status || value;
        
        return { value, label };
    });
  };

  return {
    options,
    config,
    loading,
    error,
    getOptions,
    getSelectOptions
  };
};
