'use client'

import { useState, useEffect } from 'react'

// =============================================================================
// TYPES
// =============================================================================

export interface LegalDocument {
  id: string
  type: 'privacy-policy' | 'terms' | 'cookie-policy' | 'imprint' | 'dpa'
  name: string
  version: string
  language: string
  status: 'draft' | 'active' | 'archived'
  lastUpdated: Date
  publishedAt: Date | null
  author: string
  changes: string[]
}

interface ApiDocument {
  id: string
  type: string
  name: string
  description: string
  mandatory: boolean
  created_at: string
  updated_at: string
}

// =============================================================================
// HELPERS
// =============================================================================

function mapDocumentType(apiType: string): LegalDocument['type'] {
  const mapping: Record<string, LegalDocument['type']> = {
    'privacy_policy': 'privacy-policy',
    'privacy-policy': 'privacy-policy',
    'terms': 'terms',
    'terms_of_service': 'terms',
    'cookie_policy': 'cookie-policy',
    'cookie-policy': 'cookie-policy',
    'imprint': 'imprint',
    'dpa': 'dpa',
    'avv': 'dpa',
  }
  return mapping[apiType] || 'terms'
}

function transformApiDocument(doc: ApiDocument): LegalDocument {
  return {
    id: doc.id,
    type: mapDocumentType(doc.type),
    name: doc.name,
    version: '1.0',
    language: 'de',
    status: 'active',
    lastUpdated: new Date(doc.updated_at),
    publishedAt: new Date(doc.created_at),
    author: 'System',
    changes: doc.description ? [doc.description] : [],
  }
}

// =============================================================================
// HOOK
// =============================================================================

export function useConsentDocuments() {
  const [documents, setDocuments] = useState<LegalDocument[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [previewDoc, setPreviewDoc] = useState<{ name: string; content: string } | null>(null)

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

  async function loadDocuments() {
    setLoading(true)
    setError(null)
    try {
      const token = localStorage.getItem('bp_admin_token')
      const res = await fetch('/api/admin/consent/documents', {
        headers: token ? { 'Authorization': `Bearer ${token}` } : {}
      })
      if (res.ok) {
        const data = await res.json()
        const apiDocs: ApiDocument[] = data.documents || []
        setDocuments(apiDocs.map(transformApiDocument))
      } else {
        setError('Fehler beim Laden der Dokumente')
      }
    } catch {
      setError('Verbindungsfehler zum Server')
    } finally {
      setLoading(false)
    }
  }

  async function handleRagSuggest(docType: string, docName: string): Promise<string | null> {
    const query = docType || docName || 'Datenschutzerklärung'
    try {
      const res = await fetch('/api/sdk/v1/rag/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: `${query} DSGVO Vorlage`, limit: 1 }),
      })
      if (res.ok) {
        const data = await res.json()
        const first = data.results?.[0]
        if (first?.text) return first.text
      }
    } catch { /* silently ignore */ }
    return null
  }

  async function handleCreateDocument(form: {
    type: string
    name: string
    description: string
    content: string
  }): Promise<boolean> {
    if (!form.name.trim()) return false
    try {
      const token = localStorage.getItem('bp_admin_token')
      const res = await fetch('/api/admin/consent/documents', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        },
        body: JSON.stringify(form),
      })
      if (res.ok) {
        await loadDocuments()
        return true
      } else {
        setError('Fehler beim Erstellen des Dokuments')
      }
    } catch {
      setError('Verbindungsfehler beim Erstellen')
    }
    return false
  }

  async function handleDeleteDocument(id: string) {
    if (!confirm('Dokument wirklich löschen?')) return
    try {
      const token = localStorage.getItem('bp_admin_token')
      const res = await fetch(`/api/admin/consent/documents/${id}`, {
        method: 'DELETE',
        headers: token ? { 'Authorization': `Bearer ${token}` } : {},
      })
      if (res.ok || res.status === 204) {
        setDocuments(prev => prev.filter(d => d.id !== id))
      } else {
        setError('Fehler beim Löschen des Dokuments')
      }
    } catch {
      setError('Verbindungsfehler beim Löschen')
    }
  }

  async function handlePreview(doc: LegalDocument) {
    try {
      const token = localStorage.getItem('bp_admin_token')
      const res = await fetch(`/api/admin/consent/documents/${doc.id}/versions`, {
        headers: token ? { 'Authorization': `Bearer ${token}` } : {}
      })
      if (res.ok) {
        const data = await res.json()
        const versions = Array.isArray(data) ? data : (data.versions || [])
        const published = versions.find((v: { status: string; content?: string }) => v.status === 'published')
        const latest = published || versions[0]
        setPreviewDoc({ name: doc.name, content: latest?.content || '<p>Kein Inhalt verfügbar.</p>' })
      } else {
        setPreviewDoc({ name: doc.name, content: '<p>Vorschau nicht verfügbar.</p>' })
      }
    } catch {
      setPreviewDoc({ name: doc.name, content: '<p>Fehler beim Laden der Vorschau.</p>' })
    }
  }

  return {
    documents,
    loading,
    error,
    previewDoc,
    setPreviewDoc,
    handleRagSuggest,
    handleCreateDocument,
    handleDeleteDocument,
    handlePreview,
  }
}
