'use client'

import { useState, useEffect, useCallback } from 'react'
import { WorkshopSession } from '../_components/types'
import { api } from '../_components/workshopApi'

export function useWorkshopSessions() {
  const [sessions, setSessions] = useState<WorkshopSession[]>([])
  const [loading, setLoading] = useState(true)

  const loadSessions = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api<WorkshopSession[] | { sessions: WorkshopSession[] }>('')
      const list = Array.isArray(data) ? data : (data.sessions || [])
      setSessions(list)
    } catch (err) {
      console.error('Load sessions error:', err)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { loadSessions() }, [loadSessions])

  const handleDelete = async (id: string) => {
    if (!confirm('Workshop wirklich loeschen?')) return
    try {
      await api(`/${id}`, { method: 'DELETE' })
      setSessions(prev => prev.filter(s => s.id !== id))
    } catch (err) {
      console.error('Delete error:', err)
    }
  }

  return { sessions, loading, loadSessions, handleDelete }
}
