import { useCallback, useState } from 'react'
import { parseBundleFromFiles } from './parseSongBundle'
import { parseBundlesFromZip } from './parseSongZip'
import type { SongBundle } from './types'

export function useUploadBundles() {
  const [bundles, setBundles] = useState<SongBundle[]>([])
  const [error, setError] = useState<string | null>(null)
  const [processing, setProcessing] = useState(false)
  const [dragOver, setDragOver] = useState(false)

  const handleFiles = useCallback(async (files: File[]) => {
    setError(null)
    setProcessing(true)
    try {
      const isZip = files.length === 1 && /\.zip$/i.test(files[0].name)
      const parsed = isZip ? await parseBundlesFromZip(files[0]) : await parseBundleFromFiles(files)
      setBundles((prev) => [...prev, ...parsed])
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to parse files')
    } finally {
      setProcessing(false)
    }
  }, [])

  const updateBundle = useCallback((id: string, patch: Partial<SongBundle>) => {
    setBundles((prev) => prev.map((b) => (b.id === id ? { ...b, ...patch } : b)))
  }, [])

  const removeBundle = useCallback((id: string) => {
    setBundles((prev) => prev.filter((b) => b.id !== id))
  }, [])

  return {
    bundles,
    error,
    processing,
    dragOver,
    setDragOver,
    setError,
    setProcessing,
    handleFiles,
    updateBundle,
    removeBundle,
  }
}
