import { useState, useEffect, useCallback } from 'react'
import api from '../utils/api'

export const EXERCISE_LIST_PAGE_SIZE = 100

/**
 * Lädt Kataloge für Filter/Bulk einmalig und hält die Übungsliste (Offset + Keyset „Mehr laden“) synchron zu queryBase.
 */
export function useExerciseListCatalogsAndQuery({ queryBase, pageTab, tenantClubDepKey }) {
  const [catalogs, setCatalogs] = useState({
    focusAreas: [],
    styleDirections: [],
    trainingTypes: [],
    targetGroups: [],
    skills: [],
  })
  const [catalogsReady, setCatalogsReady] = useState(false)
  const [exercises, setExercises] = useState([])
  const [listFetching, setListFetching] = useState(false)
  const [loadingMore, setLoadingMore] = useState(false)
  const [hasMore, setHasMore] = useState(false)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const [fa, sd, tt, tg, sk] = await Promise.all([
          api.listFocusAreas(),
          api.listStyleDirections(),
          api.listTrainingTypes(),
          api.listTargetGroups(),
          api.listSkills(),
        ])
        if (!cancelled) {
          setCatalogs({
            focusAreas: fa,
            styleDirections: sd,
            trainingTypes: tt,
            targetGroups: tg,
            skills: sk,
          })
          setCatalogsReady(true)
        }
      } catch (err) {
        if (!cancelled) {
          console.error(err)
          alert('Kataloge konnten nicht geladen werden: ' + err.message)
          setCatalogsReady(true)
        }
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  useEffect(() => {
    if (!catalogsReady || pageTab !== 'list') return
    let cancelled = false
    const run = async () => {
      setListFetching(true)
      try {
        const batch = await api.listExercises({
          ...queryBase,
          limit: EXERCISE_LIST_PAGE_SIZE,
          offset: 0,
        })
        if (cancelled) return
        setExercises(batch)
        setHasMore(batch.length === EXERCISE_LIST_PAGE_SIZE)
      } catch (err) {
        if (!cancelled) {
          console.error('Failed to load data:', err)
          alert('Fehler beim Laden: ' + err.message)
        }
      } finally {
        if (!cancelled) setListFetching(false)
      }
    }
    run()
    return () => {
      cancelled = true
    }
  }, [queryBase, catalogsReady, pageTab, tenantClubDepKey])

  const loadMore = useCallback(async () => {
    if (loadingMore || !hasMore) return
    const last = exercises[exercises.length - 1]
    if (!last?.id || last.updated_at == null) return
    setLoadingMore(true)
    try {
      const batch = await api.listExercises({
        ...queryBase,
        limit: EXERCISE_LIST_PAGE_SIZE,
        cursor_updated_at:
          typeof last.updated_at === 'string'
            ? last.updated_at
            : new Date(last.updated_at).toISOString(),
        cursor_id: last.id,
      })
      setExercises((prev) => [...prev, ...batch])
      setHasMore(batch.length === EXERCISE_LIST_PAGE_SIZE)
    } catch (err) {
      alert('Fehler: ' + err.message)
    } finally {
      setLoadingMore(false)
    }
  }, [loadingMore, hasMore, exercises, queryBase])

  return {
    catalogs,
    catalogsReady,
    exercises,
    setExercises,
    listFetching,
    loadingMore,
    hasMore,
    loadMore,
  }
}
