'use client'

import { useState, useEffect } from 'react'
import { 
  CpuChipIcon, 
  ServerIcon, 
  CircleStackIcon,
  GlobeAltIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ArrowPathIcon
} from '@heroicons/react/24/outline'

interface SystemInfo {
  hostname: string
  os: {
    name: string
    version: string
    arch: string
  }
  hardware: {
    cpu: {
      cores: number
      model: string
    }
    memory: {
      total: number
      available: number
    }
    storage: {
      total: number
      available: number
    }
    gpus: Array<{
      type: string
      name: string
      memory: number
    }>
  }
  network: {
    interfaces: Array<{
      name: string
      ip: string
      mac: string
      speed: string
      status: string
    }>
    primary_interface: string
    primary_ip: string
  }
  software: {
    docker: {
      installed: boolean
      version?: string
    }
    ollama: {
      installed: boolean
      type?: 'ollama' | 'parallama'
      version?: string
    }
    bzzz: {
      installed: boolean
      version?: string
    }
  }
}

interface SystemDetectionProps {
  systemInfo: SystemInfo | null
  configData: any
  onComplete: (data: any) => void
  onBack?: () => void
  isCompleted: boolean
}

export default function SystemDetection({ 
  systemInfo, 
  configData, 
  onComplete, 
  onBack, 
  isCompleted 
}: SystemDetectionProps) {
  const [loading, setLoading] = useState(!systemInfo)
  const [refreshing, setRefreshing] = useState(false)
  const [detectedInfo, setDetectedInfo] = useState<SystemInfo | null>(systemInfo)

  useEffect(() => {
    if (!detectedInfo) {
      refreshSystemInfo()
    }
  }, [])

  const refreshSystemInfo = async () => {
    setRefreshing(true)
    try {
      const response = await fetch('/api/system/detect')
      if (response.ok) {
        const info = await response.json()
        setDetectedInfo(info)
      }
    } catch (error) {
      console.error('Failed to detect system info:', error)
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  const handleContinue = () => {
    if (detectedInfo) {
      onComplete({
        system: detectedInfo,
        validated: true
      })
    }
  }

  const formatMemory = (bytes: number) => {
    return `${Math.round(bytes / (1024 ** 3))} GB`
  }

  const formatStorage = (bytes: number) => {
    return `${Math.round(bytes / (1024 ** 3))} GB`
  }

  const getStatusColor = (condition: boolean) => {
    return condition ? 'text-green-600' : 'text-red-600'
  }

  const getStatusIcon = (condition: boolean) => {
    return condition ? CheckCircleIcon : ExclamationTriangleIcon
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <ArrowPathIcon className="h-8 w-8 text-bzzz-primary animate-spin mx-auto mb-4" />
          <p className="text-gray-600">Detecting system configuration...</p>
        </div>
      </div>
    )
  }

  if (!detectedInfo) {
    return (
      <div className="text-center py-12">
        <ExclamationTriangleIcon className="h-12 w-12 text-red-500 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">
          System Detection Failed
        </h3>
        <p className="text-gray-600 mb-4">
          Unable to detect system configuration. Please try again.
        </p>
        <button
          onClick={refreshSystemInfo}
          disabled={refreshing}
          className="btn-primary"
        >
          {refreshing ? 'Retrying...' : 'Retry Detection'}
        </button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* System Overview */}
      <div className="bg-gray-50 rounded-lg p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-medium text-gray-900">System Overview</h3>
          <button
            onClick={refreshSystemInfo}
            disabled={refreshing}
            className="text-bzzz-primary hover:text-bzzz-primary/80 transition-colors"
          >
            <ArrowPathIcon className={`h-5 w-5 ${refreshing ? 'animate-spin' : ''}`} />
          </button>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <div className="text-sm font-medium text-gray-700">Hostname</div>
            <div className="text-lg text-gray-900">{detectedInfo.hostname}</div>
          </div>
          <div>
            <div className="text-sm font-medium text-gray-700">Operating System</div>
            <div className="text-lg text-gray-900">
              {detectedInfo.os.name} {detectedInfo.os.version} ({detectedInfo.os.arch})
            </div>
          </div>
        </div>
      </div>

      {/* Hardware Information */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* CPU & Memory */}
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <div className="flex items-center mb-4">
            <CpuChipIcon className="h-6 w-6 text-bzzz-primary mr-2" />
            <h3 className="text-lg font-medium text-gray-900">CPU & Memory</h3>
          </div>
          
          <div className="space-y-3">
            <div>
              <div className="text-sm font-medium text-gray-700">CPU</div>
              <div className="text-gray-900">
                {detectedInfo.hardware.cpu.cores} cores - {detectedInfo.hardware.cpu.model}
              </div>
            </div>
            <div>
              <div className="text-sm font-medium text-gray-700">Memory</div>
              <div className="text-gray-900">
                {formatMemory(detectedInfo.hardware.memory.total)} total, {' '}
                {formatMemory(detectedInfo.hardware.memory.available)} available
              </div>
            </div>
          </div>
        </div>

        {/* Storage */}
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <div className="flex items-center mb-4">
            <CircleStackIcon className="h-6 w-6 text-bzzz-primary mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Storage</h3>
          </div>
          
          <div className="space-y-3">
            <div>
              <div className="text-sm font-medium text-gray-700">Disk Space</div>
              <div className="text-gray-900">
                {formatStorage(detectedInfo.hardware.storage.total)} total, {' '}
                {formatStorage(detectedInfo.hardware.storage.available)} available
              </div>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2">
              <div 
                className="bg-bzzz-primary h-2 rounded-full"
                style={{ 
                  width: `${((detectedInfo.hardware.storage.total - detectedInfo.hardware.storage.available) / detectedInfo.hardware.storage.total) * 100}%` 
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* GPU Information */}
      {detectedInfo.hardware.gpus.length > 0 && (
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <div className="flex items-center mb-4">
            <ServerIcon className="h-6 w-6 text-bzzz-primary mr-2" />
            <h3 className="text-lg font-medium text-gray-900">
              GPU Configuration ({detectedInfo.hardware.gpus.length} GPU{detectedInfo.hardware.gpus.length !== 1 ? 's' : ''})
            </h3>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {detectedInfo.hardware.gpus.map((gpu, index) => (
              <div key={index} className="bg-gray-50 rounded-lg p-4">
                <div className="font-medium text-gray-900">{gpu.name}</div>
                <div className="text-sm text-gray-600">
                  {gpu.type.toUpperCase()} • {Math.round(gpu.memory / (1024 ** 3))} GB VRAM
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Network Information */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="flex items-center mb-4">
          <GlobeAltIcon className="h-6 w-6 text-bzzz-primary mr-2" />
          <h3 className="text-lg font-medium text-gray-900">Network Configuration</h3>
        </div>
        
        <div className="space-y-3">
          <div>
            <div className="text-sm font-medium text-gray-700">Primary Interface</div>
            <div className="text-gray-900">
              {detectedInfo.network.primary_interface} ({detectedInfo.network.primary_ip})
            </div>
          </div>
          
          {detectedInfo.network.interfaces.length > 1 && (
            <div>
              <div className="text-sm font-medium text-gray-700 mb-2">All Interfaces</div>
              <div className="space-y-2">
                {detectedInfo.network.interfaces.map((interface_, index) => (
                  <div key={index} className="flex justify-between items-center text-sm">
                    <span>{interface_.name}</span>
                    <span className="text-gray-600">{interface_.ip}</span>
                    <span className={`status-indicator ${
                      interface_.status === 'up' ? 'status-online' : 'status-offline'
                    }`}>
                      {interface_.status}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Software Requirements */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <h3 className="text-lg font-medium text-gray-900 mb-4">Software Requirements</h3>
        
        <div className="space-y-4">
          {[
            {
              name: 'Docker',
              installed: detectedInfo.software.docker.installed,
              version: detectedInfo.software.docker.version,
              required: true
            },
            {
              name: detectedInfo.software.ollama.type === 'parallama' ? 'Parallama' : 'Ollama',
              installed: detectedInfo.software.ollama.installed,
              version: detectedInfo.software.ollama.version,
              required: false
            },
            {
              name: 'BZZZ',
              installed: detectedInfo.software.bzzz.installed,
              version: detectedInfo.software.bzzz.version,
              required: true
            }
          ].map((software, index) => {
            const StatusIcon = getStatusIcon(software.installed)
            return (
              <div key={index} className="flex items-center justify-between">
                <div className="flex items-center">
                  <StatusIcon className={`h-5 w-5 mr-3 ${getStatusColor(software.installed)}`} />
                  <div>
                    <div className="font-medium text-gray-900">{software.name}</div>
                    {software.version && (
                      <div className="text-sm text-gray-600">Version: {software.version}</div>
                    )}
                  </div>
                </div>
                <div className="flex items-center">
                  {software.required && (
                    <span className="text-xs bg-bzzz-primary text-white px-2 py-1 rounded mr-2">
                      Required
                    </span>
                  )}
                  <span className={`text-sm font-medium ${getStatusColor(software.installed)}`}>
                    {software.installed ? 'Installed' : 'Missing'}
                  </span>
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* System Validation */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
        <h3 className="text-lg font-medium text-blue-900 mb-4">System Validation</h3>
        
        <div className="space-y-2">
          {[
            { 
              check: 'Minimum memory (2GB required)', 
              passed: detectedInfo.hardware.memory.total >= 2 * 1024 ** 3,
              warning: detectedInfo.hardware.memory.total < 4 * 1024 ** 3
            },
            { 
              check: 'Available disk space (10GB required)', 
              passed: detectedInfo.hardware.storage.available >= 10 * 1024 ** 3 
            },
            { 
              check: 'Docker installed and running', 
              passed: detectedInfo.software.docker.installed 
            },
            { 
              check: 'BZZZ binaries installed', 
              passed: detectedInfo.software.bzzz.installed 
            }
          ].map((validation, index) => {
            const StatusIcon = getStatusIcon(validation.passed)
            return (
              <div key={index} className="flex items-center">
                <StatusIcon className={`h-4 w-4 mr-3 ${
                  validation.passed 
                    ? 'text-green-600' 
                    : 'text-red-600'
                }`} />
                <span className={`text-sm ${
                  validation.passed 
                    ? 'text-green-800' 
                    : 'text-red-800'
                }`}>
                  {validation.check}
                  {validation.warning && validation.passed && (
                    <span className="text-yellow-600 ml-2">(Warning: Recommend 4GB+)</span>
                  )}
                </span>
              </div>
            )
          })}
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex justify-between pt-6 border-t border-gray-200">
        <div>
          {onBack && (
            <button onClick={onBack} className="btn-outline">
              Back
            </button>
          )}
        </div>
        
        <div className="flex space-x-3">
          <button
            onClick={refreshSystemInfo}
            disabled={refreshing}
            className="btn-outline"
          >
            {refreshing ? 'Refreshing...' : 'Refresh'}
          </button>
          
          <button
            onClick={handleContinue}
            className="btn-primary"
            disabled={!detectedInfo.software.docker.installed || !detectedInfo.software.bzzz.installed}
          >
            {isCompleted ? 'Continue' : 'Next: Network Configuration'}
          </button>
        </div>
      </div>
    </div>
  )
}