/**
 * useAutoInlineAiValidation Hook
 *
 * Automatically triggers inline AI validation (name/description) for rows
 * that have sufficient context when the validation step becomes ready.
 *
 * Context requirements:
 * - Name validation: company + line + name value
 * - Description validation: company + line + name + description value
 *
 * This runs once when the table is ready, firing all requests at once.
 * The blur handler in ValidationTable.tsx handles subsequent validations
 * when fields are edited.
 */

import { useEffect, useRef } from 'react';
import { apiFetch } from '@/utils/api';
import { useValidationStore } from '../store/validationStore';
import { useInitPhase } from '../store/selectors';
import {
  buildNameValidationPayload,
  buildDescriptionValidationPayload,
} from '../utils/inlineAiPayload';

/**
 * Trigger validation for a single field
 */
async function triggerValidation(
  productIndex: string,
  field: 'name' | 'description',
  payload: Record<string, unknown>
) {
  const {
    setInlineAiValidating,
    setInlineAiSuggestion,
    markInlineAiAutoValidated,
  } = useValidationStore.getState();

  const validationKey = `${productIndex}-${field}`;

  // Mark as auto-validated BEFORE calling API (prevents blur handler race condition)
  markInlineAiAutoValidated(productIndex, field);

  // Mark as validating
  setInlineAiValidating(validationKey, true);

  const endpoint = field === 'name'
    ? '/api/ai/validate/inline/name'
    : '/api/ai/validate/inline/description';

  try {
    const response = await apiFetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product: payload }),
    });

    const result = await response.json();

    if (result.success !== false) {
      setInlineAiSuggestion(productIndex, field, {
        isValid: result.isValid ?? true,
        suggestion: result.suggestion,
        issues: result.issues || [],
        latencyMs: result.latencyMs,
      });
    }
  } catch (err) {
    console.error(`[AutoInlineAI] ${field} validation error for ${productIndex}:`, err);
  } finally {
    setInlineAiValidating(validationKey, false);
  }
}

/**
 * Hook that triggers inline AI validation for all rows with sufficient context
 * when the validation step becomes ready.
 */
export function useAutoInlineAiValidation() {
  const initPhase = useInitPhase();
  const hasRunRef = useRef(false);

  useEffect(() => {
    // Only run when ready phase is reached, and only once
    if (initPhase !== 'ready' || hasRunRef.current) {
      return;
    }

    hasRunRef.current = true;

    const state = useValidationStore.getState();
    const { rows, fields, inlineAi } = state;

    console.log('[AutoInlineAI] Starting auto-validation for', rows.length, 'rows');

    let nameCount = 0;
    let descCount = 0;

    // Process all rows - fire requests immediately (no batching)
    for (const row of rows) {
      const productIndex = row.__index;
      if (!productIndex) continue;

      // Check name context: company + line + name
      const hasNameContext =
        row.company &&
        row.line &&
        row.name &&
        typeof row.name === 'string' &&
        row.name.trim();

      // Check description context: company + line + name + description with ≥10 chars
      const descriptionValue = typeof row.description === 'string' ? row.description.trim() : '';
      const hasDescContext = hasNameContext && descriptionValue.length >= 10;

      // Skip if already auto-validated (shouldn't happen on first run, but be safe)
      const nameAlreadyValidated = inlineAi.autoValidated.has(`${productIndex}-name`);
      const descAlreadyValidated = inlineAi.autoValidated.has(`${productIndex}-description`);

      // Skip if currently validating (another process started validation)
      const nameCurrentlyValidating = inlineAi.validating.has(`${productIndex}-name`);
      const descCurrentlyValidating = inlineAi.validating.has(`${productIndex}-description`);

      // Trigger name validation if context is sufficient
      if (hasNameContext && !nameAlreadyValidated && !nameCurrentlyValidating) {
        const payload = buildNameValidationPayload(row, fields, rows);
        triggerValidation(productIndex, 'name', payload);
        nameCount++;
      }

      // Trigger description validation if context is sufficient
      if (hasDescContext && !descAlreadyValidated && !descCurrentlyValidating) {
        const payload = buildDescriptionValidationPayload(row, fields);
        triggerValidation(productIndex, 'description', payload);
        descCount++;
      }
    }

    console.log(`[AutoInlineAI] Triggered ${nameCount} name validations, ${descCount} description validations`);
  }, [initPhase]);
}

export default useAutoInlineAiValidation;
