'use client'

import { useState, useEffect, useCallback } from 'react'
import { BQASMetrics, TestRun, TrendData, TabId, VOICE_SERVICE_URL } from './types'

export interface QualityDashboardState {
  activeTab: TabId
  setActiveTab: (tab: TabId) => void
  isLoading: boolean
  error: string | null
  goldenMetrics: BQASMetrics | null
  syntheticMetrics: BQASMetrics | null
  ragMetrics: BQASMetrics | null
  testRuns: TestRun[]
  trendData: TrendData | null
  isRunningGolden: boolean
  isRunningSynthetic: boolean
  isRunningRag: boolean
  fetchData: () => Promise<void>
  runGoldenTests: () => Promise<void>
  runSyntheticTests: () => Promise<void>
  runRagTests: () => Promise<void>
}

export function useQualityDashboard(): QualityDashboardState {
  const [activeTab, setActiveTab] = useState<TabId>('overview')
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const [goldenMetrics, setGoldenMetrics] = useState<BQASMetrics | null>(null)
  const [syntheticMetrics, setSyntheticMetrics] = useState<BQASMetrics | null>(null)
  const [ragMetrics, setRagMetrics] = useState<BQASMetrics | null>(null)
  const [testRuns, setTestRuns] = useState<TestRun[]>([])
  const [trendData, setTrendData] = useState<TrendData | null>(null)

  const [isRunningGolden, setIsRunningGolden] = useState(false)
  const [isRunningSynthetic, setIsRunningSynthetic] = useState(false)
  const [isRunningRag, setIsRunningRag] = useState(false)

  const fetchData = useCallback(async () => {
    setIsLoading(true)
    setError(null)

    try {
      const runsResponse = await fetch(`${VOICE_SERVICE_URL}/api/v1/bqas/runs`)
      if (runsResponse.ok) {
        const runsData = await runsResponse.json()
        setTestRuns(runsData.runs || [])
      }

      const trendResponse = await fetch(`${VOICE_SERVICE_URL}/api/v1/bqas/trend?days=30`)
      if (trendResponse.ok) {
        const trend = await trendResponse.json()
        setTrendData(trend)
      }

      const metricsResponse = await fetch(`${VOICE_SERVICE_URL}/api/v1/bqas/latest-metrics`)
      if (metricsResponse.ok) {
        const metrics = await metricsResponse.json()
        setGoldenMetrics(metrics.golden || null)
        setSyntheticMetrics(metrics.synthetic || null)
        setRagMetrics(metrics.rag || null)
      }
    } catch (err) {
      console.error('Failed to fetch BQAS data:', err)
      setError('Verbindung zum Voice-Service fehlgeschlagen')
    } finally {
      setIsLoading(false)
    }
  }, [])

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

  const runGoldenTests = async () => {
    setIsRunningGolden(true)
    try {
      const response = await fetch(`${VOICE_SERVICE_URL}/api/v1/bqas/run/golden`, { method: 'POST' })
      if (response.ok) {
        const result = await response.json()
        setGoldenMetrics(result.metrics)
        await fetchData()
      }
    } catch (err) {
      console.error('Failed to run golden tests:', err)
    } finally {
      setIsRunningGolden(false)
    }
  }

  const runSyntheticTests = async () => {
    setIsRunningSynthetic(true)
    try {
      const response = await fetch(`${VOICE_SERVICE_URL}/api/v1/bqas/run/synthetic`, { method: 'POST' })
      if (response.ok) {
        const result = await response.json()
        setSyntheticMetrics(result.metrics)
        await fetchData()
      }
    } catch (err) {
      console.error('Failed to run synthetic tests:', err)
    } finally {
      setIsRunningSynthetic(false)
    }
  }

  const runRagTests = async () => {
    setIsRunningRag(true)
    try {
      const response = await fetch(`${VOICE_SERVICE_URL}/api/v1/bqas/run/rag`, { method: 'POST' })
      if (response.ok) {
        const result = await response.json()
        setRagMetrics(result.metrics)
        await fetchData()
      }
    } catch (err) {
      console.error('Failed to run RAG tests:', err)
    } finally {
      setIsRunningRag(false)
    }
  }

  return {
    activeTab, setActiveTab,
    isLoading, error,
    goldenMetrics, syntheticMetrics, ragMetrics,
    testRuns, trendData,
    isRunningGolden, isRunningSynthetic, isRunningRag,
    fetchData, runGoldenTests, runSyntheticTests, runRagTests,
  }
}
