'use client'

import { useState, useEffect } from 'react'
import type { TrainingJob, TrainingConfig, DatasetStats, DataSource } from './types'
import {
  MOCK_JOBS,
  MOCK_STATS,
  MOCK_DATA_SOURCES,
  fetchJobs,
  fetchDatasetStats,
  createTrainingJob,
  pauseJob,
  resumeJob,
  cancelJob,
} from './api'

export type TabType = 'dashboard' | 'architecture' | 'sources'

export interface RagPipelineState {
  activeTab: TabType
  setActiveTab: (tab: TabType) => void
  jobs: TrainingJob[]
  stats: DatasetStats
  dataSources: DataSource[]
  showNewTrainingModal: boolean
  setShowNewTrainingModal: (show: boolean) => void
  selectedJob: TrainingJob | null
  setSelectedJob: (job: TrainingJob | null) => void
  isLoading: boolean
  error: string | null
  setError: (error: string | null) => void
  handleStartTraining: (config: Partial<TrainingConfig>) => Promise<void>
  handlePauseJob: (jobId: string) => Promise<void>
  handleResumeJob: (jobId: string) => Promise<void>
  handleCancelJob: (jobId: string) => Promise<void>
}

export function useRagPipeline(): RagPipelineState {
  const [activeTab, setActiveTab] = useState<TabType>('dashboard')
  const [jobs, setJobs] = useState<TrainingJob[]>([])
  const [stats, setStats] = useState<DatasetStats>(MOCK_STATS)
  const [dataSources] = useState<DataSource[]>(MOCK_DATA_SOURCES)
  const [showNewTrainingModal, setShowNewTrainingModal] = useState(false)
  const [selectedJob, setSelectedJob] = useState<TrainingJob | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    async function loadData() {
      setIsLoading(true)
      try {
        const [jobsData, statsData] = await Promise.all([
          fetchJobs(),
          fetchDatasetStats(),
        ])
        setJobs(jobsData)
        setStats(statsData)
        setError(null)
      } catch (err) {
        console.error('Failed to load data:', err)
        setError('Verbindung zum Backend fehlgeschlagen')
        setJobs(MOCK_JOBS)
        setStats(MOCK_STATS)
      } finally {
        setIsLoading(false)
      }
    }
    loadData()
  }, [])

  useEffect(() => {
    const hasActiveJob = jobs.some(j => j.status === 'training' || j.status === 'preparing')
    if (!hasActiveJob) return

    const interval = setInterval(async () => {
      try {
        const updatedJobs = await fetchJobs()
        setJobs(updatedJobs)
      } catch (err) {
        console.error('Failed to refresh jobs:', err)
      }
    }, 2000)

    return () => clearInterval(interval)
  }, [jobs])

  const handleStartTraining = async (config: Partial<TrainingConfig>) => {
    try {
      await createTrainingJob(config)
      const updatedJobs = await fetchJobs()
      setJobs(updatedJobs)
      setShowNewTrainingModal(false)
    } catch (err) {
      console.error('Failed to start training:', err)
      setError(err instanceof Error ? err.message : 'Indexierung konnte nicht gestartet werden')
    }
  }

  const handlePauseJob = async (jobId: string) => {
    try {
      await pauseJob(jobId)
      const updatedJobs = await fetchJobs()
      setJobs(updatedJobs)
    } catch (err) {
      console.error('Failed to pause job:', err)
    }
  }

  const handleResumeJob = async (jobId: string) => {
    try {
      await resumeJob(jobId)
      const updatedJobs = await fetchJobs()
      setJobs(updatedJobs)
    } catch (err) {
      console.error('Failed to resume job:', err)
    }
  }

  const handleCancelJob = async (jobId: string) => {
    try {
      await cancelJob(jobId)
      const updatedJobs = await fetchJobs()
      setJobs(updatedJobs)
    } catch (err) {
      console.error('Failed to cancel job:', err)
    }
  }

  return {
    activeTab,
    setActiveTab,
    jobs,
    stats,
    dataSources,
    showNewTrainingModal,
    setShowNewTrainingModal,
    selectedJob,
    setSelectedJob,
    isLoading,
    error,
    setError,
    handleStartTraining,
    handlePauseJob,
    handleResumeJob,
    handleCancelJob,
  }
}
