/**
 * useCopyDownValidation Hook
 *
 * Watches for copy-down operations and triggers appropriate validations:
 * - UPC-related fields (supplier, upc, barcode) -> UPC validation
 * - Line field -> Inline AI validation for rows that gain sufficient context
 *
 * This avoids duplicating validation logic - we reuse the same code paths
 * that handle individual cell blur events.
 */

import { useEffect } from 'react';
import { apiFetch } from '@/utils/api';
import { useValidationStore } from '../store/validationStore';
import { useUpcValidation } from './useUpcValidation';
import type { Field } from '../../../types';
import {
  buildNameValidationPayload,
  buildDescriptionValidationPayload,
} from '../utils/inlineAiPayload';

/**
 * Trigger inline AI validation for a single row/field
 */
async function triggerInlineAiValidation(
  rowIndex: number,
  field: 'name' | 'description',
  rows: ReturnType<typeof useValidationStore.getState>['rows'],
  fields: Field<string>[],
  setInlineAiValidating: (key: string, validating: boolean) => void,
  setInlineAiSuggestion: (productIndex: string, field: 'name' | 'description', result: { isValid: boolean; suggestion?: string; issues: string[]; latencyMs?: number }) => void
) {
  const row = rows[rowIndex];
  if (!row?.__index) return;

  const productIndex = row.__index;
  const validationKey = `${productIndex}-${field}`;

  setInlineAiValidating(validationKey, true);

  // Build payload using centralized utility
  const productPayload = field === 'name'
    ? buildNameValidationPayload(row, fields, rows)
    : buildDescriptionValidationPayload(row, fields);

  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: productPayload }),
    });

    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(`[InlineAI] ${field} validation error on line copy-down:`, err);
  } finally {
    setInlineAiValidating(validationKey, false);
  }
}

/**
 * Hook that handles validation after copy-down operations.
 * Should be called once in ValidationContainer to ensure validation runs.
 */
export const useCopyDownValidation = () => {
  const { validateUpc } = useUpcValidation();

  // Subscribe to pending validations
  const pendingUpcValidation = useValidationStore((state) => state.pendingCopyDownValidation);
  const pendingInlineAiValidation = useValidationStore((state) => state.pendingInlineAiValidation);
  const clearPendingCopyDownValidation = useValidationStore((state) => state.clearPendingCopyDownValidation);
  const clearPendingInlineAiValidation = useValidationStore((state) => state.clearPendingInlineAiValidation);

  // Handle UPC validation
  useEffect(() => {
    if (!pendingUpcValidation) return;

    const { affectedRows } = pendingUpcValidation;
    const rows = useValidationStore.getState().rows;

    const validationPromises = affectedRows.map(async (rowIndex) => {
      const row = rows[rowIndex];
      if (!row) return;

      const supplierId = row.supplier ? String(row.supplier) : '';
      const upcValue = row.upc ? String(row.upc) : (row.barcode ? String(row.barcode) : '');

      if (supplierId && upcValue) {
        await validateUpc(rowIndex, supplierId, upcValue);
      }
    });

    Promise.all(validationPromises).then(() => {
      clearPendingCopyDownValidation();
    });
  }, [pendingUpcValidation, validateUpc, clearPendingCopyDownValidation]);

  // Handle inline AI validation (triggered by line copy-down)
  useEffect(() => {
    if (!pendingInlineAiValidation) return;

    const { nameRows, descriptionRows } = pendingInlineAiValidation;
    const state = useValidationStore.getState();
    const { rows, fields, setInlineAiValidating, setInlineAiSuggestion } = state;

    console.log(`[InlineAI] Line copy-down: validating ${nameRows.length} names, ${descriptionRows.length} descriptions`);

    const validationPromises: Promise<void>[] = [];

    // Trigger name validation for applicable rows
    for (const rowIndex of nameRows) {
      validationPromises.push(
        triggerInlineAiValidation(rowIndex, 'name', rows, fields, setInlineAiValidating, setInlineAiSuggestion)
      );
    }

    // Trigger description validation for applicable rows
    for (const rowIndex of descriptionRows) {
      validationPromises.push(
        triggerInlineAiValidation(rowIndex, 'description', rows, fields, setInlineAiValidating, setInlineAiSuggestion)
      );
    }

    Promise.all(validationPromises).then(() => {
      clearPendingInlineAiValidation();
    });
  }, [pendingInlineAiValidation, clearPendingInlineAiValidation]);
};
