'use client'

import { useState } from 'react'
import { Document, Version, ApprovalHistoryItem } from '../_types'
import type { ApprovalModalMode } from '../_components/ApprovalModal'

interface UseWorkflowActionsParams {
  selectedDocument: Document | null
  setDocuments: React.Dispatch<React.SetStateAction<Document[]>>
  setSelectedDocument: React.Dispatch<React.SetStateAction<Document | null>>
  draftVersion: Version | null
  currentVersion: Version | null
  versions: Version[]
  editedTitle: string
  editedContent: string
  editedSummary: string
  loadVersions: (docId: string) => Promise<void>
  setError: (msg: string | null) => void
}

export function useWorkflowActions(params: UseWorkflowActionsParams) {
  const {
    selectedDocument, setDocuments, setSelectedDocument,
    draftVersion, currentVersion, versions,
    editedTitle, editedContent, editedSummary,
    loadVersions, setError,
  } = params

  const [saving, setSaving] = useState(false)
  const [approvalComment, setApprovalComment] = useState('')
  const [showApprovalModal, setShowApprovalModal] = useState<ApprovalModalMode | null>(null)
  const [approvalHistory, setApprovalHistory] = useState<ApprovalHistoryItem[]>([])
  const [showNewDocModal, setShowNewDocModal] = useState(false)
  const [newDocForm, setNewDocForm] = useState({ type: 'privacy_policy', name: '', description: '' })
  const [creatingDoc, setCreatingDoc] = useState(false)

  const getNextVersionNumber = () => {
    if (versions.length === 0) return '1.0'
    const latest = versions[0]
    const parts = latest.version.split('.')
    const major = parseInt(parts[0]) || 1
    const minor = parseInt(parts[1]) || 0
    return `${major}.${minor + 1}`
  }

  const createNewDraft = async () => {
    if (!selectedDocument) return
    setSaving(true)
    try {
      const nextVersion = getNextVersionNumber()
      const res = await fetch('/api/admin/consent/versions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          document_id: selectedDocument.id,
          version: nextVersion,
          language: 'de',
          title: editedTitle || currentVersion?.title || selectedDocument.name,
          content: editedContent || currentVersion?.content || '',
          summary: editedSummary || currentVersion?.summary || '',
        }),
      })

      if (res.ok) {
        await loadVersions(selectedDocument.id)
      } else {
        const err = await res.json()
        setError(err.error || 'Fehler beim Erstellen des Entwurfs')
      }
    } catch {
      setError('Fehler beim Erstellen des Entwurfs')
    } finally {
      setSaving(false)
    }
  }

  const saveDraft = async () => {
    if (!draftVersion || draftVersion.status !== 'draft') return
    setSaving(true)
    try {
      const res = await fetch(`/api/admin/consent/versions/${draftVersion.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: editedTitle,
          content: editedContent,
          summary: editedSummary,
        }),
      })

      if (res.ok) {
        await loadVersions(selectedDocument!.id)
      } else {
        const err = await res.json()
        setError(err.error || 'Fehler beim Speichern')
      }
    } catch {
      setError('Fehler beim Speichern')
    } finally {
      setSaving(false)
    }
  }

  const submitForReview = async () => {
    if (!draftVersion) return
    setSaving(true)
    try {
      const res = await fetch(`/api/admin/consent/versions/${draftVersion.id}/submit-review`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })

      if (res.ok) {
        await loadVersions(selectedDocument!.id)
      } else {
        const err = await res.json()
        setError(err.error || 'Fehler beim Einreichen')
      }
    } catch {
      setError('Fehler beim Einreichen zur Pruefung')
    } finally {
      setSaving(false)
    }
  }

  const approveVersion = async () => {
    // Backward-compat alias — leitet auf approve-internal (DSB → Mandant)
    return approveInternal()
  }

  const approveInternal = async () => {
    if (!draftVersion) return
    setSaving(true)
    try {
      const res = await fetch(`/api/admin/consent/versions/${draftVersion.id}/approve-internal`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ comment: approvalComment }),
      })

      if (res.ok) {
        setShowApprovalModal(null)
        setApprovalComment('')
        await loadVersions(selectedDocument!.id)
      } else {
        const err = await res.json()
        setError(err.error || 'Fehler bei der DSB-Freigabe')
      }
    } catch {
      setError('Fehler bei der DSB-Freigabe')
    } finally {
      setSaving(false)
    }
  }

  const approveClient = async () => {
    if (!draftVersion) return
    setSaving(true)
    try {
      const res = await fetch(`/api/admin/consent/versions/${draftVersion.id}/approve-client`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ comment: approvalComment }),
      })

      if (res.ok) {
        setShowApprovalModal(null)
        setApprovalComment('')
        await loadVersions(selectedDocument!.id)
      } else {
        const err = await res.json()
        setError(err.error || 'Fehler bei der Mandanten-Freigabe')
      }
    } catch {
      setError('Fehler bei der Mandanten-Freigabe')
    } finally {
      setSaving(false)
    }
  }

  const rejectVersion = async () => {
    if (!draftVersion) return
    setSaving(true)
    try {
      const res = await fetch(`/api/admin/consent/versions/${draftVersion.id}/reject`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason: approvalComment }),
      })

      if (res.ok) {
        setShowApprovalModal(null)
        setApprovalComment('')
        await loadVersions(selectedDocument!.id)
      } else {
        const err = await res.json()
        setError(err.error || 'Fehler bei der Ablehnung')
      }
    } catch {
      setError('Fehler bei der Ablehnung')
    } finally {
      setSaving(false)
    }
  }

  const publishVersion = async () => {
    if (!draftVersion || draftVersion.status !== 'approved') return
    if (!confirm('Version wirklich veroeffentlichen? Die aktuelle Version wird archiviert.')) return

    setSaving(true)
    try {
      const res = await fetch(`/api/admin/consent/versions/${draftVersion.id}/publish`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })

      if (res.ok) {
        await loadVersions(selectedDocument!.id)
      } else {
        const err = await res.json()
        setError(err.error || 'Fehler beim Veroeffentlichen')
      }
    } catch {
      setError('Fehler beim Veroeffentlichen')
    } finally {
      setSaving(false)
    }
  }

  const createDocument = async () => {
    if (!newDocForm.name.trim()) return
    setCreatingDoc(true)
    try {
      const res = await fetch('/api/admin/consent/documents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newDocForm),
      })
      if (res.ok) {
        const newDoc: Document = await res.json()
        setDocuments(prev => [newDoc, ...prev])
        setSelectedDocument(newDoc)
        setShowNewDocModal(false)
        setNewDocForm({ type: 'privacy_policy', name: '', description: '' })
      } else {
        setError('Fehler beim Erstellen des Dokuments')
      }
    } catch {
      setError('Verbindungsfehler beim Erstellen')
    } finally {
      setCreatingDoc(false)
    }
  }

  const loadApprovalHistory = async (versionId: string) => {
    try {
      const res = await fetch(`/api/admin/consent/versions/${versionId}/approval-history`)
      if (res.ok) {
        const data = await res.json()
        setApprovalHistory(data.approval_history || [])
      }
    } catch {
      console.error('Failed to load approval history')
    }
  }

  return {
    saving,
    approvalComment, setApprovalComment,
    showApprovalModal, setShowApprovalModal,
    approvalHistory,
    showNewDocModal, setShowNewDocModal,
    newDocForm, setNewDocForm,
    creatingDoc,
    createNewDraft, saveDraft, submitForReview,
    approveVersion, approveInternal, approveClient,
    rejectVersion, publishVersion,
    createDocument, loadApprovalHistory,
  }
}
