'use client'

/**
 * CI/CD Dashboard
 *
 * Zentrale Uebersicht fuer:
 * - Gitea Actions Pipelines
 * - Runner Status
 * - Container Deployments
 * - Pipeline Konfiguration
 */

import { useState, useEffect, useCallback } from 'react'
import { PagePurpose } from '@/components/common/PagePurpose'
import { DevOpsPipelineSidebarResponsive } from '@/components/infrastructure/DevOpsPipelineSidebar'
import type { PipelineStatus, PipelineRun, SystemStats, DockerStats, TabType } from './types'
import { OverviewTab } from './_components/OverviewTab'
import { PipelinesTab } from './_components/PipelinesTab'
import { DeploymentsTab } from './_components/DeploymentsTab'
import { SetupTab } from './_components/SetupTab'
import { SchedulerTab } from './_components/SchedulerTab'

export default function CICDPage() {
  const [activeTab, setActiveTab] = useState<TabType>('overview')

  // Pipeline State
  const [pipelineStatus, setPipelineStatus] = useState<PipelineStatus | null>(null)
  const [pipelineHistory, setPipelineHistory] = useState<PipelineRun[]>([])
  const [triggeringPipeline, setTriggeringPipeline] = useState(false)

  // Container State
  const [systemStats, setSystemStats] = useState<SystemStats | null>(null)
  const [dockerStats, setDockerStats] = useState<DockerStats | null>(null)
  const [containerFilter, setContainerFilter] = useState<'all' | 'running' | 'stopped'>('all')
  const [actionLoading, setActionLoading] = useState<string | null>(null)

  // General State
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [message, setMessage] = useState<string | null>(null)

  const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || ''

  // Data Loading
  const loadPipelineData = useCallback(async () => {
    try {
      const [statusRes, historyRes] = await Promise.all([
        fetch(`${BACKEND_URL}/api/v1/security/sbom/pipeline/status`),
        fetch(`${BACKEND_URL}/api/v1/security/sbom/pipeline/history`),
      ])
      if (statusRes.ok) setPipelineStatus(await statusRes.json())
      if (historyRes.ok) setPipelineHistory(await historyRes.json())
    } catch (err) {
      console.error('Failed to load pipeline data:', err)
    }
  }, [BACKEND_URL])

  const loadContainerData = useCallback(async () => {
    try {
      const response = await fetch('/api/admin/infrastructure/mac-mini')
      if (response.ok) {
        const data = await response.json()
        setSystemStats(data.system)
        setDockerStats(data.docker)
      }
    } catch (err) {
      console.error('Failed to load container data:', err)
    }
  }, [])

  const loadAllData = useCallback(async () => {
    setLoading(true)
    setError(null)
    await Promise.all([loadPipelineData(), loadContainerData()])
    setLoading(false)
  }, [loadPipelineData, loadContainerData])

  useEffect(() => { loadAllData() }, [loadAllData])
  useEffect(() => {
    const interval = setInterval(loadAllData, 30000)
    return () => clearInterval(interval)
  }, [loadAllData])

  // Actions
  const triggerPipeline = async () => {
    setTriggeringPipeline(true)
    try {
      const response = await fetch(`${BACKEND_URL}/api/v1/security/sbom/pipeline/trigger`, { method: 'POST' })
      if (response.ok) {
        setMessage('Pipeline gestartet!')
        setTimeout(loadPipelineData, 2000)
        setTimeout(loadPipelineData, 5000)
      }
    } catch (err) {
      setError('Pipeline-Trigger fehlgeschlagen')
    } finally {
      setTriggeringPipeline(false)
    }
  }

  const containerAction = async (containerId: string, action: 'start' | 'stop' | 'restart') => {
    setActionLoading(`${containerId}-${action}`)
    setMessage(null)
    try {
      const response = await fetch('/api/admin/infrastructure/mac-mini', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ container_id: containerId, action }),
      })
      if (!response.ok) throw new Error('Aktion fehlgeschlagen')
      setMessage(`Container ${action} erfolgreich`)
      setTimeout(loadContainerData, 1000)
      setTimeout(loadContainerData, 3000)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Fehler')
    } finally {
      setActionLoading(null)
    }
  }

  const filteredContainers = dockerStats?.containers.filter(c => {
    if (containerFilter === 'all') return true
    if (containerFilter === 'running') return c.state === 'running'
    if (containerFilter === 'stopped') return c.state !== 'running'
    return true
  }) || []

  const TAB_CONFIG = [
    { id: 'overview' as const, name: 'Uebersicht', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg> },
    { id: 'pipelines' as const, name: 'Gitea Pipelines', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg> },
    { id: 'deployments' as const, name: 'Deployments', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2" /></svg> },
    { id: 'setup' as const, name: 'Konfiguration', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg> },
    { id: 'scheduler' as const, name: 'BQAS Scheduler', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg> },
  ]

  return (
    <div>
      <PagePurpose
        title="CI/CD Dashboard"
        purpose="Zentrale Uebersicht fuer Gitea Actions Pipelines, Runner-Status und Container-Deployments. Starten Sie Pipelines manuell und verwalten Sie Docker-Container."
        audience={['DevOps', 'Entwickler']}
        architecture={{ services: ['Gitea Actions', 'act_runner', 'Docker'], databases: [] }}
        relatedPages={[
          { name: 'SBOM', href: '/infrastructure/sbom', description: 'Software Bill of Materials' },
          { name: 'Security', href: '/infrastructure/security', description: 'DevSecOps Dashboard' },
          { name: 'Test Quality', href: '/ai/test-quality', description: 'BQAS Test Dashboard' },
        ]}
        collapsible={true}
        defaultCollapsed={true}
      />

      <DevOpsPipelineSidebarResponsive currentTool="ci-cd" />

      {error && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-6">
          <div className="flex items-center gap-2 text-red-800">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span className="font-medium">{error}</span>
          </div>
        </div>
      )}

      {message && (
        <div className="bg-green-50 border border-green-200 rounded-xl p-4 mb-6">
          <div className="flex items-center gap-2 text-green-800">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
            <span className="font-medium">{message}</span>
          </div>
        </div>
      )}

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="flex border-b border-slate-200">
          <nav className="flex">
            {TAB_CONFIG.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-6 py-4 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${
                  activeTab === tab.id
                    ? 'border-orange-500 text-orange-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                {tab.icon}
                {tab.name}
              </button>
            ))}
          </nav>
        </div>

        <div className="p-6">
          {loading ? (
            <div className="flex justify-center py-12">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-600" />
            </div>
          ) : (
            <>
              {activeTab === 'overview' && <OverviewTab pipelineStatus={pipelineStatus} pipelineHistory={pipelineHistory} systemStats={systemStats} dockerStats={dockerStats} />}
              {activeTab === 'pipelines' && <PipelinesTab pipelineHistory={pipelineHistory} triggeringPipeline={triggeringPipeline} onTriggerPipeline={triggerPipeline} />}
              {activeTab === 'deployments' && <DeploymentsTab dockerStats={dockerStats} containerFilter={containerFilter} setContainerFilter={setContainerFilter} filteredContainers={filteredContainers} onContainerAction={containerAction} actionLoading={actionLoading} onRefresh={loadContainerData} />}
              {activeTab === 'setup' && <SetupTab pipelineStatus={pipelineStatus} />}
              {activeTab === 'scheduler' && <SchedulerTab />}
            </>
          )}
        </div>
      </div>
    </div>
  )
}
