'use client'

import { useState, useEffect } from 'react'
import type { Export, Regulation } from './types'

const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000'

export function useExport() {
  const [exports, setExports] = useState<Export[]>([])
  const [regulations, setRegulations] = useState<Regulation[]>([])
  const [loading, setLoading] = useState(true)
  const [generating, setGenerating] = useState(false)

  const [wizardStep, setWizardStep] = useState(1)
  const [exportType, setExportType] = useState('full')
  const [selectedRegulations, setSelectedRegulations] = useState<string[]>([])
  const [selectedDomains, setSelectedDomains] = useState<string[]>([])
  const [currentExport, setCurrentExport] = useState<Export | null>(null)

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

  const loadData = async () => {
    setLoading(true)
    try {
      const [exportsRes, regulationsRes] = await Promise.all([
        fetch(`${BACKEND_URL}/api/v1/compliance/exports`),
        fetch(`${BACKEND_URL}/api/v1/compliance/regulations`),
      ])

      if (exportsRes.ok) {
        const data = await exportsRes.json()
        setExports(data.exports || [])
      }
      if (regulationsRes.ok) {
        const data = await regulationsRes.json()
        setRegulations(data.regulations || [])
      }
    } catch (error) {
      console.error('Failed to load data:', error)
    } finally {
      setLoading(false)
    }
  }

  const startExport = async () => {
    setGenerating(true)
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/export`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          export_type: exportType,
          included_regulations: selectedRegulations.length > 0 ? selectedRegulations : null,
          included_domains: selectedDomains.length > 0 ? selectedDomains : null,
        }),
      })

      if (res.ok) {
        const exportData = await res.json()
        setCurrentExport(exportData)
        setWizardStep(4)
        loadData()
      } else {
        const error = await res.text()
        alert(`Export fehlgeschlagen: ${error}`)
      }
    } catch (error) {
      console.error('Export failed:', error)
      alert('Export fehlgeschlagen')
    } finally {
      setGenerating(false)
    }
  }

  const downloadExport = (exportId: string) => {
    window.open(`${BACKEND_URL}/api/v1/compliance/export/${exportId}/download`, '_blank')
  }

  const resetWizard = () => {
    setWizardStep(1)
    setExportType('full')
    setSelectedRegulations([])
    setSelectedDomains([])
    setCurrentExport(null)
  }

  const toggleRegulation = (code: string) => {
    setSelectedRegulations((prev) =>
      prev.includes(code) ? prev.filter((r) => r !== code) : [...prev, code]
    )
  }

  const toggleDomain = (domain: string) => {
    setSelectedDomains((prev) =>
      prev.includes(domain) ? prev.filter((d) => d !== domain) : [...prev, domain]
    )
  }

  return {
    exports, regulations, loading, generating,
    wizardStep, setWizardStep,
    exportType, setExportType,
    selectedRegulations, selectedDomains,
    currentExport,
    startExport, downloadExport, resetWizard,
    toggleRegulation, toggleDomain,
  }
}
