'use client'

/**
 * DevOps Pipeline Sidebar
 *
 * Kompakte Sidebar-Komponente fuer Cross-Navigation zwischen DevOps-Modulen.
 * Zeigt Pipeline-Flow und ermoeglicht schnelle Navigation.
 *
 * Features:
 * - Desktop: Fixierte Sidebar rechts
 * - Mobile: Floating Action Button mit Slide-In Drawer
 * - Live Pipeline-Status Badge
 * - Backlog-Count Badge
 * - Security-Findings-Count Badge
 * - Quick-Action: Pipeline triggern
 *
 * Datenfluss: CI/CD -> Tests -> SBOM -> Security
 */

import Link from 'next/link'
import { useState, useEffect } from 'react'
import type {
  DevOpsToolId,
  DevOpsPipelineSidebarProps,
  DevOpsPipelineSidebarResponsiveProps,
  PipelineLiveStatus,
} from '@/types/infrastructure-modules'
import { DEVOPS_PIPELINE_MODULES } from '@/types/infrastructure-modules'

// =============================================================================
// Icons
// =============================================================================

const ToolIcon = ({ id }: { id: DevOpsToolId }) => {
  switch (id) {
    case 'ci-cd':
      return (
        <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>
      )
    case 'tests':
      return (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
            d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      )
    case 'sbom':
      return (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
            d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
        </svg>
      )
    case 'security':
      return (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
            d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
        </svg>
      )
    default:
      return null
  }
}

// Server/Pipeline Icon fuer Header
const ServerIcon = () => (
  <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-2m-2-4h.01M17 16h.01" />
  </svg>
)

// Play Icon fuer Quick Action
const PlayIcon = () => (
  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
      d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
      d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
)

// =============================================================================
// Live Status Hook (optional - fetches status from API)
// =============================================================================

function usePipelineLiveStatus(): PipelineLiveStatus | null {
  const [status, setStatus] = useState<PipelineLiveStatus | null>(null)

  useEffect(() => {
    // Optional: Fetch live status from API
    // For now, return null and display static content
    // Uncomment below to enable live status fetching
    /*
    const fetchStatus = async () => {
      try {
        const response = await fetch('/api/admin/infrastructure/woodpecker/status')
        if (response.ok) {
          const data = await response.json()
          setStatus(data)
        }
      } catch (error) {
        console.error('Failed to fetch pipeline status:', error)
      }
    }
    fetchStatus()
    const interval = setInterval(fetchStatus, 30000) // Poll every 30s
    return () => clearInterval(interval)
    */
  }, [])

  return status
}

// =============================================================================
// Status Badge Component
// =============================================================================

interface StatusBadgeProps {
  count: number
  type: 'backlog' | 'security' | 'running'
}

function StatusBadge({ count, type }: StatusBadgeProps) {
  if (count === 0) return null

  const colors = {
    backlog: 'bg-amber-500',
    security: 'bg-red-500',
    running: 'bg-green-500 animate-pulse',
  }

  return (
    <span className={`${colors[type]} text-white text-xs font-medium px-1.5 py-0.5 rounded-full min-w-[1.25rem] text-center`}>
      {count}
    </span>
  )
}

// =============================================================================
// Main Sidebar Component
// =============================================================================

export function DevOpsPipelineSidebar({
  currentTool,
  compact = false,
  className = '',
}: DevOpsPipelineSidebarProps) {
  const [isExpanded, setIsExpanded] = useState(!compact)
  const liveStatus = usePipelineLiveStatus()

  return (
    <div className={`bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-slate-200 dark:border-gray-700 overflow-hidden ${className}`}>
      {/* Header */}
      <div
        className="px-4 py-3 bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 border-b border-slate-200 dark:border-gray-700 cursor-pointer"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="text-orange-600 dark:text-orange-400">
              <ServerIcon />
            </span>
            <span className="font-semibold text-slate-700 dark:text-slate-200 text-sm">
              DevOps Pipeline
            </span>
            {/* Live status indicator */}
            {liveStatus?.isRunning && (
              <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" title="Pipeline laeuft" />
            )}
          </div>
          <svg
            className={`w-4 h-4 text-slate-400 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </div>
      </div>

      {/* Content */}
      {isExpanded && (
        <div className="p-3 space-y-3">
          {/* Tool Links */}
          <div className="space-y-1">
            {DEVOPS_PIPELINE_MODULES.map((tool) => (
              <Link
                key={tool.id}
                href={tool.href}
                className={`flex items-center gap-3 px-3 py-2 rounded-lg transition-colors ${
                  currentTool === tool.id
                    ? 'bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300 font-medium'
                    : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-gray-700'
                }`}
              >
                <ToolIcon id={tool.id} />
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium truncate">{tool.name}</div>
                  <div className="text-xs text-slate-500 dark:text-slate-500 truncate">
                    {tool.description}
                  </div>
                </div>
                {/* Status badges */}
                {tool.id === 'tests' && liveStatus && (
                  <StatusBadge count={liveStatus.backlogCount} type="backlog" />
                )}
                {tool.id === 'security' && liveStatus && (
                  <StatusBadge count={liveStatus.securityFindingsCount} type="security" />
                )}
                {currentTool === tool.id && (
                  <span className="flex-shrink-0 w-2 h-2 bg-orange-500 rounded-full" />
                )}
              </Link>
            ))}
          </div>

          {/* Pipeline Flow Visualization */}
          <div className="pt-2 border-t border-slate-200 dark:border-gray-700">
            <div className="text-xs font-medium text-slate-500 dark:text-slate-400 mb-2 px-1">
              Pipeline Flow
            </div>
            <div className="flex items-center justify-between px-2 py-2 bg-slate-50 dark:bg-gray-900 rounded-lg">
              <div className="flex items-center gap-1.5 text-xs">
                <span title="Code" className={currentTool === 'ci-cd' ? 'opacity-100' : 'opacity-50'}>📝</span>
                <span className="text-slate-400">→</span>
                <span title="Build" className={currentTool === 'ci-cd' ? 'opacity-100' : 'opacity-50'}>🏗️</span>
                <span className="text-slate-400">→</span>
                <span title="Test" className={currentTool === 'tests' ? 'opacity-100' : 'opacity-50'}>✅</span>
                <span className="text-slate-400">→</span>
                <span title="SBOM" className={currentTool === 'sbom' ? 'opacity-100' : 'opacity-50'}>📦</span>
                <span className="text-slate-400">→</span>
                <span title="Security" className={currentTool === 'security' ? 'opacity-100' : 'opacity-50'}>🛡️</span>
                <span className="text-slate-400">→</span>
                <span title="Deploy" className="opacity-50">🚀</span>
              </div>
            </div>
          </div>

          {/* Quick Info zum aktuellen Tool */}
          <div className="pt-2 border-t border-slate-200 dark:border-gray-700">
            <div className="text-xs text-slate-500 dark:text-slate-400 px-1">
              {currentTool === 'ci-cd' && (
                <span>Verwalten Sie Woodpecker Pipelines und Deployments</span>
              )}
              {currentTool === 'tests' && (
                <span>Ueberwachen Sie 280+ Tests ueber alle Services</span>
              )}
              {currentTool === 'sbom' && (
                <span>Pruefen Sie Abhaengigkeiten und Lizenzen</span>
              )}
              {currentTool === 'security' && (
                <span>Analysieren Sie Vulnerabilities und Security-Scans</span>
              )}
            </div>
          </div>

          {/* Quick Action: Pipeline triggern */}
          <div className="pt-2 border-t border-slate-200 dark:border-gray-700">
            <button
              onClick={() => {
                // TODO: Implement pipeline trigger
                alert('Pipeline wird getriggert...')
              }}
              className="w-full flex items-center justify-center gap-2 px-3 py-2 text-sm text-orange-600 dark:text-orange-400 bg-orange-50 dark:bg-orange-900/20 hover:bg-orange-100 dark:hover:bg-orange-900/30 rounded-lg transition-colors"
            >
              <PlayIcon />
              <span>Pipeline triggern</span>
            </button>
          </div>
        </div>
      )}
    </div>
  )
}

// Re-export responsive version for backwards compatibility
export { DevOpsPipelineSidebarResponsive } from './DevOpsPipelineSidebarResponsive'

export default DevOpsPipelineSidebar
