'use client'

import { useState, useEffect } from 'react'
import type { TrainingJob, TrainingConfig, DatasetStats } from './_components/types'
import { MOCK_JOBS, MOCK_STATS, fetchJobs, fetchDatasetStats, createTrainingJob, pauseJob, resumeJob, cancelJob } from './_components/api'
import { TrainingJobCard } from './_components/TrainingJobCard'
import { DatasetOverview } from './_components/DatasetOverview'
import { NewTrainingModal } from './_components/NewTrainingModal'
import { QuickActions } from './_components/QuickActions'

export default function TrainingDashboardPage() {
  const [jobs, setJobs] = useState<TrainingJob[]>([])
  const [stats, setStats] = useState<DatasetStats>(MOCK_STATS)
  const [showNewTrainingModal, setShowNewTrainingModal] = useState(false)
  const [selectedJob, setSelectedJob] = useState<TrainingJob | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Load initial data
  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()
  }, [])

  // Real-time updates for active training jobs
  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 : 'Training konnte nicht gestartet werden')
    }
  }

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

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

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

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex justify-between items-start mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Training Dashboard</h1>
            <p className="text-gray-500 dark:text-gray-400 mt-1">
              Überwachen und steuern Sie KI-Trainingsprozesse für Zeugnisse
            </p>
          </div>
          <button
            onClick={() => setShowNewTrainingModal(true)}
            className="px-6 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-medium rounded-xl shadow-lg hover:shadow-xl transition-all hover:-translate-y-0.5"
          >
            <span className="flex items-center gap-2">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              Neues Training
            </span>
          </button>
        </div>

        {/* Error Banner */}
        {error && (
          <div className="mb-6 p-4 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-700 rounded-xl">
            <div className="flex items-center gap-3">
              <span className="text-amber-500">&#9888;</span>
              <span className="text-amber-800 dark:text-amber-200">{error}</span>
              <button onClick={() => setError(null)} className="ml-auto text-amber-600 hover:text-amber-800">&#10005;</button>
            </div>
          </div>
        )}

        {/* Loading State */}
        {isLoading ? (
          <div className="flex items-center justify-center py-20">
            <div className="text-center">
              <div className="w-12 h-12 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin mx-auto mb-4" />
              <p className="text-gray-500 dark:text-gray-400">Lade Trainingsdaten...</p>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-3 gap-6">
            {/* Training Jobs */}
            <div className="col-span-2 space-y-6">
              {jobs.length === 0 ? (
                <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg p-12 text-center">
                  <div className="w-16 h-16 mx-auto mb-4 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center">
                    <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                    </svg>
                  </div>
                  <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">Kein aktives Training</h3>
                  <p className="text-gray-500 dark:text-gray-400 mb-6">Starten Sie ein neues Training, um das Zeugnis-Modell zu verbessern.</p>
                  <button onClick={() => setShowNewTrainingModal(true)} className="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700">Training starten</button>
                </div>
              ) : (
                jobs.map(job => (
                  <TrainingJobCard
                    key={job.id}
                    job={job}
                    onPause={() => handlePauseJob(job.id)}
                    onResume={() => handleResumeJob(job.id)}
                    onStop={() => handleCancelJob(job.id)}
                    onViewDetails={() => setSelectedJob(job)}
                  />
                ))
              )}
            </div>

            {/* Sidebar */}
            <div className="space-y-6">
              <DatasetOverview stats={stats} />
              <QuickActions />
            </div>
          </div>
        )}
      </div>

      <NewTrainingModal
        isOpen={showNewTrainingModal}
        onClose={() => setShowNewTrainingModal(false)}
        onSubmit={handleStartTraining}
      />
    </div>
  )
}
