'use client'

import { useState, useEffect, useMemo } from 'react'
import type { SBOMData, CategoryType, InfoTabType, SbomStats, CategoryItem, Component } from './types'
import {
  INFRASTRUCTURE_COMPONENTS,
  SECURITY_TOOLS,
  PYTHON_PACKAGES,
  GO_MODULES,
  NODE_PACKAGES,
  UNITY_PACKAGES,
  CSHARP_PACKAGES,
} from './data'

export function useSbomData() {
  const [sbomData, setSbomData] = useState<SBOMData | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeCategory, setActiveCategory] = useState<CategoryType>('all')
  const [searchTerm, setSearchTerm] = useState('')
  const [activeInfoTab, setActiveInfoTab] = useState<InfoTabType>('audit')
  const [showFullDocs, setShowFullDocs] = useState(false)

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

  const loadSBOM = async () => {
    setLoading(true)
    try {
      const res = await fetch('/api/v1/security/sbom')
      if (res.ok) {
        const data = await res.json()
        setSbomData(data)
      }
    } catch (error) {
      console.error('Failed to load SBOM:', error)
    } finally {
      setLoading(false)
    }
  }

  const getAllComponents = (): Component[] => {
    const infraComponents = INFRASTRUCTURE_COMPONENTS.map(c => ({ ...c, category: c.category || 'infrastructure' }))
    const securityToolsComponents = SECURITY_TOOLS.map(c => ({ ...c, category: c.category || 'security-tool' }))
    const pythonComponents = PYTHON_PACKAGES.map(c => ({ ...c, category: 'python' as const }))
    const goComponents = GO_MODULES.map(c => ({ ...c, category: 'go' as const }))
    const nodeComponents = NODE_PACKAGES.map(c => ({ ...c, category: 'nodejs' as const }))
    const unityComponents = UNITY_PACKAGES.map(c => ({ ...c, category: 'unity' as const }))
    const csharpComponents = CSHARP_PACKAGES.map(c => ({ ...c, category: 'csharp' as const }))
    const dynamicPython = (sbomData?.components || []).map(c => ({ ...c, category: 'python' as const }))

    return [
      ...infraComponents, ...securityToolsComponents, ...pythonComponents,
      ...goComponents, ...nodeComponents, ...unityComponents,
      ...csharpComponents, ...dynamicPython,
    ]
  }

  const filteredComponents = useMemo(() => {
    let components: Component[]

    if (activeCategory === 'all') {
      components = getAllComponents()
    } else if (activeCategory === 'infrastructure') {
      components = INFRASTRUCTURE_COMPONENTS
    } else if (activeCategory === 'security-tools') {
      components = SECURITY_TOOLS
    } else if (activeCategory === 'python') {
      components = [...PYTHON_PACKAGES, ...(sbomData?.components || [])]
    } else if (activeCategory === 'go') {
      components = GO_MODULES
    } else if (activeCategory === 'nodejs') {
      components = NODE_PACKAGES
    } else if (activeCategory === 'unity') {
      components = UNITY_PACKAGES
    } else if (activeCategory === 'csharp') {
      components = CSHARP_PACKAGES
    } else {
      components = getAllComponents()
    }

    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      components = components.filter(c =>
        c.name.toLowerCase().includes(term) ||
        c.version.toLowerCase().includes(term) ||
        (c.description?.toLowerCase().includes(term))
      )
    }

    return components
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeCategory, searchTerm, sbomData])

  const stats: SbomStats = useMemo(() => ({
    totalInfra: INFRASTRUCTURE_COMPONENTS.length,
    totalSecurityTools: SECURITY_TOOLS.length,
    totalPython: PYTHON_PACKAGES.length + (sbomData?.components?.length || 0),
    totalGo: GO_MODULES.length,
    totalNode: NODE_PACKAGES.length,
    totalUnity: UNITY_PACKAGES.length,
    totalCsharp: CSHARP_PACKAGES.length,
    totalAll: INFRASTRUCTURE_COMPONENTS.length + SECURITY_TOOLS.length + PYTHON_PACKAGES.length + GO_MODULES.length + NODE_PACKAGES.length + UNITY_PACKAGES.length + CSHARP_PACKAGES.length + (sbomData?.components?.length || 0),
    databases: INFRASTRUCTURE_COMPONENTS.filter(c => c.category === 'database').length,
    services: INFRASTRUCTURE_COMPONENTS.filter(c => c.category === 'application').length,
    communication: INFRASTRUCTURE_COMPONENTS.filter(c => c.category === 'communication').length,
    game: INFRASTRUCTURE_COMPONENTS.filter(c => c.category === 'game').length,
  }), [sbomData])

  const categories: CategoryItem[] = useMemo(() => [
    { id: 'all', name: 'Alle', count: stats.totalAll },
    { id: 'infrastructure', name: 'Infrastruktur', count: stats.totalInfra },
    { id: 'security-tools', name: 'Security Tools', count: stats.totalSecurityTools },
    { id: 'python', name: 'Python', count: stats.totalPython },
    { id: 'go', name: 'Go', count: stats.totalGo },
    { id: 'nodejs', name: 'Node.js', count: stats.totalNode },
    { id: 'unity', name: 'Unity', count: stats.totalUnity },
    { id: 'csharp', name: 'C#', count: stats.totalCsharp },
  ], [stats])

  const handleExport = () => {
    const data = JSON.stringify({
      ...sbomData,
      infrastructure: INFRASTRUCTURE_COMPONENTS
    }, null, 2)
    const blob = new Blob([data], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `breakpilot-lehrer-sbom-${new Date().toISOString().split('T')[0]}.json`
    a.click()
  }

  return {
    sbomData,
    loading,
    activeCategory,
    setActiveCategory,
    searchTerm,
    setSearchTerm,
    activeInfoTab,
    setActiveInfoTab,
    showFullDocs,
    setShowFullDocs,
    filteredComponents,
    stats,
    categories,
    handleExport,
  }
}
