'use client'
import { useState, useEffect, useCallback } from 'react'
import { pb } from '@/lib/pocketbase'

interface UsePBCollectionResult<T> {
  items: T[]
  loading: boolean
  error: string | null
  refresh: () => void
}

export function usePBCollection<T>(
  collection: string,
  options?: Record<string, unknown>,
): UsePBCollectionResult<T> {
  const [items, setItems] = useState<T[]>([])
  const [loading, setLoading] = useState<boolean>(true)
  const [error, setError] = useState<string | null>(null)
  const [tick, setTick] = useState<number>(0)

  const refresh = useCallback(() => {
    setTick((t) => t + 1)
  }, [])

  useEffect(() => {
    let cancelled = false

    async function load() {
      setLoading(true)
      setError(null)
      try {
        const result = await pb.collection(collection).getFullList<T>({
          ...(options ?? {}),
        })
        if (!cancelled) {
          setItems(result)
        }
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : 'Failed to load')
        }
      } finally {
        if (!cancelled) {
          setLoading(false)
        }
      }
    }

    void load()
    return () => {
      cancelled = true
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [collection, tick])

  return { items, loading, error, refresh }
}
