'use client'

import { useState, useEffect } from 'react'
import type { Tab, Document, Version } from './types'
import { API_BASE } from './types'

export function useConsent() {
  const [activeTab, setActiveTab] = useState<Tab>('documents')
  const [documents, setDocuments] = useState<Document[]>([])
  const [versions, setVersions] = useState<Version[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [selectedDocument, setSelectedDocument] = useState<string>('')
  const [authToken, setAuthToken] = useState<string>('')

  useEffect(() => {
    const token = localStorage.getItem('bp_admin_token')
    if (token) {
      setAuthToken(token)
    }
  }, [])

  useEffect(() => {
    if (activeTab === 'documents') {
      loadDocuments()
    } else if (activeTab === 'versions' && selectedDocument) {
      loadVersions(selectedDocument)
    }
  }, [activeTab, selectedDocument, authToken])

  async function loadDocuments() {
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`${API_BASE}/documents`, {
        headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {}
      })
      if (res.ok) {
        const data = await res.json()
        setDocuments(data.documents || [])
      } else {
        const errorData = await res.json().catch(() => ({}))
        setError(errorData.error || 'Fehler beim Laden der Dokumente')
      }
    } catch (err) {
      setError('Verbindungsfehler zum Server')
    } finally {
      setLoading(false)
    }
  }

  async function loadVersions(docId: string) {
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`${API_BASE}/documents/${docId}/versions`, {
        headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {}
      })
      if (res.ok) {
        const data = await res.json()
        setVersions(data.versions || [])
      } else {
        const errorData = await res.json().catch(() => ({}))
        setError(errorData.error || 'Fehler beim Laden der Versionen')
      }
    } catch (err) {
      setError('Verbindungsfehler zum Server')
    } finally {
      setLoading(false)
    }
  }

  return {
    activeTab, setActiveTab,
    documents, versions,
    loading, error, setError,
    selectedDocument, setSelectedDocument,
    authToken, setAuthToken,
  }
}
