import { useState, useEffect, useCallback } from 'react'
import { integrationsApi } from '../lib/integrationsApi'

/**
 * Laedt die InvoiceNinja-Rechnungen eines verknuepften Clients.
 * clientId = customers.invoiceNinjaClientId (oder null -> nichts laden).
 */
export function useInvoices(clientId) {
  const [invoices, setInvoices] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const fetchInvoices = useCallback(async () => {
    if (!clientId) {
      setInvoices([])
      return
    }
    setLoading(true)
    setError(null)
    try {
      const data = await integrationsApi.listInvoices(clientId)
      setInvoices(data.invoices || [])
    } catch (err) {
      setError(err.message)
      setInvoices([])
    } finally {
      setLoading(false)
    }
  }, [clientId])

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

  const createInvoice = useCallback(
    async (payload) => {
      try {
        const data = await integrationsApi.createInvoice(payload)
        await fetchInvoices()
        return { success: true, invoice: data.invoice }
      } catch (err) {
        return { success: false, error: err.message }
      }
    },
    [fetchInvoices]
  )

  return { invoices, loading, error, refresh: fetchInvoices, createInvoice }
}
