/**
 * Hook for translating reasoning_data structures
 *
 * Handles translation of structured backend reasoning data into
 * user-friendly, multilingual text for the JTBD dashboard.
 */

import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';

export interface ReasoningData {
  type: string;
  parameters: Record<string, any>;
  consequence?: {
    type: string;
    severity?: string;
    impact_days?: number;
    [key: string]: any;
  };
  urgency?: {
    level?: string;
    [key: string]: any;
  };
  metadata?: Record<string, any>;
}

export function useReasoningTranslation() {
  const { t } = useTranslation('reasoning');

  /**
   * Translate purchase order reasoning
   * IMPORTANT: Always returns a string, never undefined
   */
  const translatePOReasonng = (reasoningData: ReasoningData): string => {
    if (!reasoningData || !reasoningData.type) {
      const fallback = t('purchaseOrder.low_stock_detection', {
        supplier_name: 'Unknown',
        product_names_joined: 'Items',
        days_until_stockout: 7,
        defaultValue: 'Purchase order required for inventory replenishment'
      });
      return String(fallback || 'Purchase order required');
    }

    const { type, parameters } = reasoningData;

    // Join product names if array
    const params = {
      ...parameters,
      product_names_joined: Array.isArray(parameters.product_names)
        ? parameters.product_names.join(', ')
        : parameters.product_names || 'Items',
      defaultValue: `Purchase order: ${type}`
    };

    const result = t(`purchaseOrder.${type}`, params);
    return String(result || `Purchase order: ${type}`);
  };

  /**
   * Translate production batch reasoning
   * IMPORTANT: Always returns a string, never undefined
   */
  const translateBatchReasoning = (reasoningData: ReasoningData): string => {
    if (!reasoningData || !reasoningData.type) {
      const fallback = t('productionBatch.forecast_demand', {
        product_name: 'Product',
        predicted_demand: 0,
        current_stock: 0,
        confidence_score: 85,
        defaultValue: 'Production batch scheduled based on demand forecast'
      });
      return String(fallback || 'Production batch scheduled');
    }

    const { type, parameters } = reasoningData;
    const params = {
      ...parameters,
      defaultValue: `Production batch: ${type}`
    };
    const result = t(`productionBatch.${type}`, params);
    return String(result || `Production batch: ${type}`);
  };

  /**
   * Translate consequence text
   * IMPORTANT: Always returns a string, never undefined
   */
  const translateConsequence = (consequenceData?: any): string => {
    if (!consequenceData || !consequenceData.type) {
      return '';
    }

    const params = {
      ...consequenceData,
      affected_products_joined: Array.isArray(consequenceData.affected_products)
        ? consequenceData.affected_products.join(', ')
        : consequenceData.affected_products || 'products',
      defaultValue: `Impact: ${consequenceData.type}`
    };

    const result = t(`consequence.${consequenceData.type}`, params);
    return String(result || '');
  };

  /**
   * Translate severity level
   * IMPORTANT: Always returns a string, never undefined
   */
  const translateSeverity = (severity?: string): string => {
    if (!severity) return '';
    const result = t(`severity.${severity}`, { defaultValue: severity });
    return String(result || '');
  };

  /**
   * Translate trigger source
   * IMPORTANT: Always returns a string, never undefined
   */
  const translateTrigger = (trigger?: string): string => {
    if (!trigger) return '';
    const result = t(`triggers.${trigger}`, { defaultValue: trigger });
    return String(result || '');
  };

  /**
   * Translate error code
   * IMPORTANT: Always returns a string, never undefined
   */
  const translateError = (errorCode: string): string => {
    const result = t(`errors.${errorCode}`, { defaultValue: errorCode });
    return String(result || errorCode);
  };

  return {
    translatePOReasonng,
    translateBatchReasoning,
    translateConsequence,
    translateSeverity,
    translateTrigger,
    translateError,
    t, // Expose the raw t function for direct access
  };
}

/**
 * Format reasoning data for display
 * Combines reasoning and consequence into a cohesive message
 */
export function useReasoningFormatter() {
  const translation = useReasoningTranslation();

  const formatPOAction = useCallback((reasoningData?: ReasoningData) => {
    if (!reasoningData) {
      return {
        reasoning: String(translation.translatePOReasonng({} as ReasoningData) || 'Purchase order required'),
        consequence: String(''),
        severity: String('')
      };
    }

    const reasoning = String(translation.translatePOReasonng(reasoningData) || 'Purchase order required');
    const consequence = String(translation.translateConsequence(reasoningData.consequence) || '');
    const severity = String(translation.translateSeverity(reasoningData.consequence?.severity) || '');

    return { reasoning, consequence, severity };
  }, [translation]);

  const formatBatchAction = useCallback((reasoningData?: ReasoningData) => {
    if (!reasoningData) {
      return {
        reasoning: String(translation.translateBatchReasoning({} as ReasoningData) || 'Production batch scheduled'),
        urgency: String('normal')
      };
    }

    const reasoning = String(translation.translateBatchReasoning(reasoningData) || 'Production batch scheduled');
    const urgency = String(reasoningData.urgency?.level || 'normal');

    return { reasoning, urgency };
  }, [translation]);

  return {
    formatPOAction,
    formatBatchAction,
    ...translation
  };
}
