'use client'

import { useState, useMemo } from 'react'
import { useVendorCompliance, ReportType, ExportFormat } from '@/lib/sdk/vendor-compliance'
import { REPORT_TYPE_META } from '../_components/ReportTypeGrid'
import { GeneratedReport } from '../_components/RecentReports'

export function useReportExport() {
  const { processingActivities, vendors, contracts, findings, riskAssessments, isLoading } = useVendorCompliance()

  const [selectedReportType, setSelectedReportType] = useState<ReportType>('VVT_EXPORT')
  const [selectedFormat, setSelectedFormat] = useState<ExportFormat>('DOCX')
  const [selectedVendors, setSelectedVendors] = useState<string[]>([])
  const [selectedActivities, setSelectedActivities] = useState<string[]>([])
  const [includeFindings, setIncludeFindings] = useState(true)
  const [includeControls, setIncludeControls] = useState(true)
  const [includeRiskAssessment, setIncludeRiskAssessment] = useState(true)
  const [isGenerating, setIsGenerating] = useState(false)
  const [generatedReports, setGeneratedReports] = useState<GeneratedReport[]>([])

  const handleReportTypeChange = (type: ReportType) => {
    setSelectedReportType(type)
    setSelectedFormat(REPORT_TYPE_META[type].defaultFormat)
    setSelectedVendors([])
    setSelectedActivities([])
  }

  const stats = useMemo(() => {
    const openFindings = findings.filter((f) => f.status === 'OPEN').length
    const criticalFindings = findings.filter((f) => f.status === 'OPEN' && f.severity === 'CRITICAL').length
    const highRiskVendors = vendors.filter((v) => v.inherentRiskScore >= 70).length
    return {
      totalActivities: processingActivities.length,
      approvedActivities: processingActivities.filter((a) => a.status === 'APPROVED').length,
      totalVendors: vendors.length,
      activeVendors: vendors.filter((v) => v.status === 'ACTIVE').length,
      totalContracts: contracts.length,
      openFindings,
      criticalFindings,
      highRiskVendors,
    }
  }, [processingActivities, vendors, contracts, findings])

  const handleExport = async () => {
    setIsGenerating(true)
    try {
      const config = {
        reportType: selectedReportType,
        format: selectedFormat,
        scope: {
          vendorIds: selectedVendors,
          processingActivityIds: selectedActivities,
          includeFindings,
          includeControls,
          includeRiskAssessment,
        },
      }
      const response = await fetch('/api/sdk/v1/vendor-compliance/export', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config),
      })
      if (!response.ok) throw new Error('Export fehlgeschlagen')
      const result = await response.json()
      setGeneratedReports((prev) => [
        { id: result.id, type: selectedReportType, format: selectedFormat, generatedAt: new Date(), filename: result.filename },
        ...prev,
      ])
      if (result.downloadUrl) window.open(result.downloadUrl, '_blank')
    } catch (error) {
      console.error('Export error:', error)
    } finally {
      setIsGenerating(false)
    }
  }

  const toggleVendor = (vendorId: string) =>
    setSelectedVendors((prev) =>
      prev.includes(vendorId) ? prev.filter((id) => id !== vendorId) : [...prev, vendorId]
    )

  const toggleActivity = (activityId: string) =>
    setSelectedActivities((prev) =>
      prev.includes(activityId) ? prev.filter((id) => id !== activityId) : [...prev, activityId]
    )

  const selectAllVendors = () => setSelectedVendors(vendors.map((v) => v.id))
  const selectAllActivities = () => setSelectedActivities(processingActivities.map((a) => a.id))

  return {
    processingActivities,
    vendors,
    isLoading,
    selectedReportType,
    selectedFormat,
    setSelectedFormat,
    selectedVendors,
    selectedActivities,
    includeFindings,
    setIncludeFindings,
    includeControls,
    setIncludeControls,
    includeRiskAssessment,
    setIncludeRiskAssessment,
    isGenerating,
    generatedReports,
    stats,
    handleReportTypeChange,
    handleExport,
    toggleVendor,
    toggleActivity,
    selectAllVendors,
    selectAllActivities,
  }
}
