/**
 * useInlineAiValidation Hook
 *
 * Provides inline AI validation for product names and descriptions.
 * Calls the backend Groq-powered validation endpoints.
 */

import { useState, useCallback, useRef } from 'react';
import { apiFetch } from '@/utils/api';

// Types for the validation results
export interface InlineAiResult {
  isValid: boolean;
  suggestion: string | null;
  issues: string[];
  latencyMs?: number;
}

export interface InlineAiValidationState {
  isValidating: boolean;
  error: string | null;
  nameResult: InlineAiResult | null;
  descriptionResult: InlineAiResult | null;
}

// Product data structure for validation
// Note: company_id is needed by backend to load company-specific prompts, but line_id/subline_id are not needed
export interface ProductForValidation {
  name?: string;
  description?: string;
  company_name?: string;
  company_id?: string;  // Needed by backend for prompt loading (not sent to AI model)
  line_name?: string;
  subline_name?: string;
  categories?: string;
  // Sibling context for naming decisions
  siblingNames?: string[];
}

// Debounce delay in milliseconds
const DEBOUNCE_DELAY = 500;

/**
 * Hook for inline AI validation of product fields
 */
export function useInlineAiValidation() {
  const [state, setState] = useState<InlineAiValidationState>({
    isValidating: false,
    error: null,
    nameResult: null,
    descriptionResult: null
  });

  // Track pending requests for cancellation
  const abortControllerRef = useRef<AbortController | null>(null);
  const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

  /**
   * Validate a product name
   */
  const validateName = useCallback(async (product: ProductForValidation): Promise<InlineAiResult | null> => {
    if (!product.name?.trim()) {
      return null;
    }

    // Cancel any pending request
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    const controller = new AbortController();
    abortControllerRef.current = controller;

    setState(prev => ({ ...prev, isValidating: true, error: null }));

    try {
      const response = await apiFetch('/api/ai/validate/inline/name', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ product }),
        signal: controller.signal
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || `Validation failed: ${response.status}`);
      }

      const result = await response.json();

      const aiResult: InlineAiResult = {
        isValid: result.isValid ?? true,
        suggestion: result.suggestion || null,
        issues: result.issues || [],
        latencyMs: result.latencyMs
      };

      setState(prev => ({
        ...prev,
        isValidating: false,
        nameResult: aiResult,
        error: null
      }));

      return aiResult;
    } catch (error) {
      if ((error as Error).name === 'AbortError') {
        // Request was cancelled, ignore
        return null;
      }

      const message = (error as Error).message || 'Validation failed';
      setState(prev => ({
        ...prev,
        isValidating: false,
        error: message
      }));

      return null;
    }
  }, []);

  /**
   * Validate a product description
   */
  const validateDescription = useCallback(async (product: ProductForValidation): Promise<InlineAiResult | null> => {
    if (!product.name?.trim() && !product.description?.trim()) {
      return null;
    }

    // Cancel any pending request
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    const controller = new AbortController();
    abortControllerRef.current = controller;

    setState(prev => ({ ...prev, isValidating: true, error: null }));

    try {
      const response = await apiFetch('/api/ai/validate/inline/description', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ product }),
        signal: controller.signal
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || `Validation failed: ${response.status}`);
      }

      const result = await response.json();

      const aiResult: InlineAiResult = {
        isValid: result.isValid ?? true,
        suggestion: result.suggestion || null,
        issues: result.issues || [],
        latencyMs: result.latencyMs
      };

      setState(prev => ({
        ...prev,
        isValidating: false,
        descriptionResult: aiResult,
        error: null
      }));

      return aiResult;
    } catch (error) {
      if ((error as Error).name === 'AbortError') {
        // Request was cancelled, ignore
        return null;
      }

      const message = (error as Error).message || 'Validation failed';
      setState(prev => ({
        ...prev,
        isValidating: false,
        error: message
      }));

      return null;
    }
  }, []);

  /**
   * Debounced name validation - call on blur or after typing stops
   */
  const validateNameDebounced = useCallback((product: ProductForValidation) => {
    // Clear existing timer
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    debounceTimerRef.current = setTimeout(() => {
      validateName(product);
    }, DEBOUNCE_DELAY);
  }, [validateName]);

  /**
   * Debounced description validation
   */
  const validateDescriptionDebounced = useCallback((product: ProductForValidation) => {
    // Clear existing timer
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    debounceTimerRef.current = setTimeout(() => {
      validateDescription(product);
    }, DEBOUNCE_DELAY);
  }, [validateDescription]);

  /**
   * Clear validation results
   */
  const clearResults = useCallback(() => {
    // Cancel any pending requests
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }

    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
      debounceTimerRef.current = null;
    }

    setState({
      isValidating: false,
      error: null,
      nameResult: null,
      descriptionResult: null
    });
  }, []);

  /**
   * Clear name result only
   */
  const clearNameResult = useCallback(() => {
    setState(prev => ({ ...prev, nameResult: null }));
  }, []);

  /**
   * Clear description result only
   */
  const clearDescriptionResult = useCallback(() => {
    setState(prev => ({ ...prev, descriptionResult: null }));
  }, []);

  return {
    // State
    isValidating: state.isValidating,
    error: state.error,
    nameResult: state.nameResult,
    descriptionResult: state.descriptionResult,

    // Actions - immediate
    validateName,
    validateDescription,

    // Actions - debounced
    validateNameDebounced,
    validateDescriptionDebounced,

    // Clear
    clearResults,
    clearNameResult,
    clearDescriptionResult
  };
}
