import { useCallback, useState } from 'react'

import { WildberriesService } from '@/services/wildberries-service'

import type { UseProductPhotosReturn } from '../types'

/**
 * Хук для управления фотографиями товаров
 */
export function useProductPhotos(): UseProductPhotosReturn {
  const [productPhotos, setProductPhotos] = useState<Map<number, string>>(new Map())

  const loadProductPhotos = useCallback(async (nmIds: number[]) => {
    const newPhotos = new Map(productPhotos)
    let hasNewPhotos = false

    for (const nmId of nmIds) {
      if (!newPhotos.has(nmId)) {
        try {
          const photoUrl = await (WildberriesService as any).getProductPhoto(nmId)
          if (photoUrl) {
            newPhotos.set(nmId, photoUrl)
            hasNewPhotos = true
          }
        } catch (error) {
          console.error(`Error loading photo for product ${nmId}:`, error)
          // Устанавливаем пустую строку, чтобы не повторять загрузку
          newPhotos.set(nmId, '')
        }
      }
    }

    if (hasNewPhotos) {
      setProductPhotos(newPhotos)
    }
  }, [productPhotos])

  return {
    productPhotos,
    loadProductPhotos,
  }
}