/**
 * useProductSuggestions Hook
 *
 * Lazily fetches embedding-based taxonomy suggestions (categories, themes, colors)
 * for a product in the product editor.
 *
 * Mirrors the logic in AiSuggestionsContext but simplified for single-product use:
 * - Fetches once on first triggerFetch() call (no eager batch loading)
 * - Caches results in local state for the lifetime of the component
 * - Module-level init promise shared across all instances
 */

import { useState, useRef, useCallback, useEffect } from 'react';
import { apiFetch } from '@/utils/api';
import type { TaxonomySuggestion, ProductSuggestions } from '@/components/product-import/steps/ValidationStep/store/types';

const API_BASE = '/api/ai';

// Module-level init promise — shared so we only call /initialize once
let initPromise: Promise<boolean> | null = null;

async function ensureInitialized(): Promise<boolean> {
  if (!initPromise) {
    initPromise = apiFetch(`${API_BASE}/initialize`, { method: 'POST' })
      .then((r) => r.json())
      .then((d) => Boolean(d.success))
      .catch(() => {
        initPromise = null; // allow retry on next call
        return false;
      });
  }
  return initPromise;
}

interface ProductInput {
  name?: string;
  description?: string;
  company_name?: string;
  line_name?: string;
}

export interface ProductSuggestionResults {
  categories: TaxonomySuggestion[];
  themes: TaxonomySuggestion[];
  colors: TaxonomySuggestion[];
  isLoading: boolean;
  /** Call when a taxonomy dropdown opens to trigger a lazy fetch */
  triggerFetch: () => void;
}

export function useProductSuggestions(product: ProductInput): ProductSuggestionResults {
  const [categories, setCategories] = useState<TaxonomySuggestion[]>([]);
  const [themes, setThemes] = useState<TaxonomySuggestion[]>([]);
  const [colors, setColors] = useState<TaxonomySuggestion[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  // Store current product in a ref so triggerFetch can read it without being re-created
  const productRef = useRef(product);
  productRef.current = product;

  // Pre-warm: start initialization as soon as the form mounts so it's ready before
  // the first dropdown opens. With the disk cache this completes in < 1 second.
  useEffect(() => {
    ensureInitialized();
  }, []);

  // Prevent duplicate fetches
  const hasFetchedRef = useRef(false);

  const triggerFetch = useCallback(async () => {
    if (hasFetchedRef.current) return;
    const p = productRef.current;
    if (!p.name && !p.company_name) return;

    hasFetchedRef.current = true;
    setIsLoading(true);

    try {
      const ready = await ensureInitialized();
      if (!ready) {
        hasFetchedRef.current = false;
        return;
      }

      const response = await apiFetch(`${API_BASE}/suggestions`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ product: p }),
      });

      if (!response.ok) {
        hasFetchedRef.current = false;
        return;
      }

      const data: ProductSuggestions = await response.json();
      setCategories(data.categories ?? []);
      setThemes(data.themes ?? []);
      setColors(data.colors ?? []);
    } catch {
      hasFetchedRef.current = false;
    } finally {
      setIsLoading(false);
    }
  }, []);

  return { categories, themes, colors, isLoading, triggerFetch };
}
