import { useMemo } from 'react'
import type { CategoryTemplate, TemplateDetail } from '@repo/sdk'

/**
 * Template type that can be filtered (supports both CategoryTemplate and TemplateDetail)
 */
type FilterableTemplate = CategoryTemplate | TemplateDetail

/**
 * Options for useTemplateFilter hook
 */
export interface UseTemplateFilterOptions<T extends FilterableTemplate = FilterableTemplate> {
  templates: T[]
  excludeVideo?: boolean
}

/**
 * Return type for useTemplateFilter hook
 */
export interface UseTemplateFilterReturn<T extends FilterableTemplate = FilterableTemplate> {
  filteredTemplates: T[]
}

/**
 * Video file extensions to filter out
 */
const VIDEO_EXTENSIONS = ['mp4', 'mov', 'webm']

/**
 * Hook to filter templates by type (exclude video templates)
 *
 * @param options - Filter options
 * @param options.templates - Array of templates to filter
 * @param options.excludeVideo - Whether to exclude video templates (default: false)
 * @returns Object containing filtered templates
 */
export function useTemplateFilter<T extends FilterableTemplate>(options: UseTemplateFilterOptions<T>): UseTemplateFilterReturn<T> {
  const { templates, excludeVideo = false } = options

  const filteredTemplates = useMemo(() => {
    if (!excludeVideo) {
      return templates
    }

    return templates.filter(template => {
      const previewUrl = template.webpPreviewUrl || template.previewUrl || template.coverImageUrl || ''
      const ext = previewUrl.split('.').pop()?.toLowerCase()
      return !VIDEO_EXTENSIONS.includes(ext || '')
    })
  }, [templates, excludeVideo])

  return {
    filteredTemplates,
  }
}
