'use client'

import { useState, useEffect } from 'react'
import { ChevronRightIcon, CheckCircleIcon } from '@heroicons/react/24/outline'
import SystemDetection from './components/SystemDetection'
import NetworkConfiguration from './components/NetworkConfiguration'
import SecuritySetup from './components/SecuritySetup'
import AIConfiguration from './components/AIConfiguration'
import ResourceAllocation from './components/ResourceAllocation'
import ServiceDeployment from './components/ServiceDeployment'
import ClusterFormation from './components/ClusterFormation'
import TestingValidation from './components/TestingValidation'

const SETUP_STEPS = [
  {
    id: 'detection',
    title: 'System Detection',
    description: 'Detect hardware and validate installation',
    component: SystemDetection,
  },
  {
    id: 'network',
    title: 'Network Configuration',
    description: 'Configure network and firewall settings',
    component: NetworkConfiguration,
  },
  {
    id: 'security',
    title: 'Security Setup',
    description: 'Configure authentication and SSH access',
    component: SecuritySetup,
  },
  {
    id: 'ai',
    title: 'AI Integration',
    description: 'Configure OpenAI and Ollama/Parallama',
    component: AIConfiguration,
  },
  {
    id: 'resources',
    title: 'Resource Allocation',
    description: 'Allocate CPU, memory, and storage',
    component: ResourceAllocation,
  },
  {
    id: 'deployment',
    title: 'Service Deployment',
    description: 'Deploy and configure BZZZ services',
    component: ServiceDeployment,
  },
  {
    id: 'cluster',
    title: 'Cluster Formation',
    description: 'Join or create BZZZ cluster',
    component: ClusterFormation,
  },
  {
    id: 'testing',
    title: 'Testing & Validation',
    description: 'Validate configuration and test connectivity',
    component: TestingValidation,
  },
]

interface ConfigData {
  [key: string]: any
}

export default function SetupPage() {
  const [currentStep, setCurrentStep] = useState(0)
  const [completedSteps, setCompletedSteps] = useState(new Set<number>())
  const [configData, setConfigData] = useState<ConfigData>({})
  const [systemInfo, setSystemInfo] = useState<any>(null)

  // Load system information on mount
  useEffect(() => {
    fetchSystemInfo()
  }, [])

  const fetchSystemInfo = async () => {
    try {
      const response = await fetch('/api/system/info')
      if (response.ok) {
        const info = await response.json()
        setSystemInfo(info)
      }
    } catch (error) {
      console.error('Failed to fetch system info:', error)
    }
  }

  const handleStepComplete = (stepIndex: number, data: any) => {
    setCompletedSteps(prev => new Set([...prev, stepIndex]))
    setConfigData(prev => ({ ...prev, ...data }))
    
    // Auto-advance to next step
    if (stepIndex < SETUP_STEPS.length - 1) {
      setCurrentStep(stepIndex + 1)
    }
  }

  const handleStepBack = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1)
    }
  }

  const CurrentStepComponent = SETUP_STEPS[currentStep].component

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">
          Welcome to BZZZ Setup
        </h1>
        <p className="text-lg text-gray-600">
          Let's configure your distributed AI coordination cluster in {SETUP_STEPS.length} simple steps.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
        {/* Progress Sidebar */}
        <div className="lg:col-span-1">
          <div className="card sticky top-8">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">
              Setup Progress
            </h2>
            <nav className="space-y-2">
              {SETUP_STEPS.map((step, index) => {
                const isCompleted = completedSteps.has(index)
                const isCurrent = index === currentStep
                const isAccessible = index <= currentStep || completedSteps.has(index)

                return (
                  <button
                    key={step.id}
                    onClick={() => isAccessible && setCurrentStep(index)}
                    disabled={!isAccessible}
                    className={`w-full text-left p-3 rounded-lg border transition-all duration-200 ${
                      isCurrent
                        ? 'border-bzzz-primary bg-bzzz-primary bg-opacity-10 text-bzzz-primary'
                        : isCompleted
                        ? 'border-green-200 bg-green-50 text-green-700'
                        : isAccessible
                        ? 'border-gray-200 hover:border-gray-300 text-gray-700'
                        : 'border-gray-100 text-gray-400 cursor-not-allowed'
                    }`}
                  >
                    <div className="flex items-center">
                      <div className="flex-shrink-0 mr-3">
                        {isCompleted ? (
                          <CheckCircleIcon className="h-5 w-5 text-green-500" />
                        ) : (
                          <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center text-xs font-medium ${
                            isCurrent
                              ? 'border-bzzz-primary bg-bzzz-primary text-white'
                              : 'border-gray-300 text-gray-500'
                          }`}>
                            {index + 1}
                          </div>
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium truncate">
                          {step.title}
                        </div>
                        <div className="text-xs opacity-75 truncate">
                          {step.description}
                        </div>
                      </div>
                      {isAccessible && !isCompleted && (
                        <ChevronRightIcon className="h-4 w-4 opacity-50" />
                      )}
                    </div>
                  </button>
                )
              })}
            </nav>
            
            <div className="mt-6 pt-4 border-t border-gray-200">
              <div className="text-sm text-gray-600 mb-2">
                Progress: {completedSteps.size} of {SETUP_STEPS.length} steps
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className="bg-bzzz-primary h-2 rounded-full transition-all duration-500"
                  style={{ width: `${(completedSteps.size / SETUP_STEPS.length) * 100}%` }}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="lg:col-span-3">
          <div className="card">
            <div className="mb-6">
              <div className="flex items-center justify-between mb-2">
                <h2 className="text-2xl font-bold text-gray-900">
                  {SETUP_STEPS[currentStep].title}
                </h2>
                <div className="text-sm text-gray-500">
                  Step {currentStep + 1} of {SETUP_STEPS.length}
                </div>
              </div>
              <p className="text-gray-600">
                {SETUP_STEPS[currentStep].description}
              </p>
            </div>

            <CurrentStepComponent
              systemInfo={systemInfo}
              configData={configData}
              onComplete={(data: any) => handleStepComplete(currentStep, data)}
              onBack={currentStep > 0 ? handleStepBack : undefined}
              isCompleted={completedSteps.has(currentStep)}
            />
          </div>
        </div>
      </div>
    </div>
  )
}