/**
 * Wizard Floating Panel
 * 
 * A compact, fixed-position panel pinned to the bottom-left corner.
 * Persists across all admin pages during onboarding.
 * 
 * IMPORTANT: Layout-critical properties (width, maxWidth, maxHeight, overflow)
 * use inline styles because WordPress admin CSS and our own global overrides
 * (e.g. overflow: visible !important) can beat Tailwind class specificity.
 * 
 * @package BoostBot
 */

import { ChevronLeft, ChevronRight, ChevronDown, ChevronUp, SkipForward, Sparkles, Minus, Rocket, Settings, LocateFixed } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { useWizard } from '@/contexts/WizardContext'
import { executePingTargetsInstant, STEP_PING_TARGETS } from './wizardPing'
import { WizardStepList } from './WizardStepList'
import { WizardStreamingMessage } from './WizardStreamingMessage'
import { WizardHelpButton } from './WizardHelpButton'
import { useState } from 'react'
import { t, sprintf, getDirection } from '@/lib/i18n'

export function WizardFloatingPanel() {
  const wizard = useWizard()
  const panelNavigate = useNavigate()
  const [isMinimized, setIsMinimized] = useState(false)

  if (!wizard || !wizard.isWizardActive) return null

  const {
    steps,
    currentStepIndex,
    currentStep,
    progress,
    isExpanded,
    toggleExpanded,
    goToStep,
    goToNextStep,
    goToPrevStep,
    skipStep,
    markStepCompleted,
    streamingMessage,
    isStreaming,
  } = wizard

  // Exclude the "start" step (index 0) from progress display
  const realSteps = steps.slice(1)
  const realCompletedCount = realSteps.filter(s => progress[s.id]).length
  const progressPercent = Math.round((realCompletedCount / realSteps.length) * 100)
  const isStartPhase = currentStep?.id === 'start'
  const isFirstStep = currentStepIndex === 0
  const isLastStep = currentStepIndex === steps.length - 1

  const wizardSide = getDirection() === 'rtl' ? 'left' : 'right'

  // Minimized: show a sleek pill
  if (isMinimized) {
    return (
      <button
        onClick={() => setIsMinimized(false)}
        onMouseEnter={(e) => {
          e.currentTarget.style.background = 'linear-gradient(to right, #3BC2D0, #2BA8B5)'
          e.currentTarget.style.boxShadow = '0 20px 25px -5px rgba(59,194,208,0.3), 0 8px 10px -6px rgba(59,194,208,0.2)'
          e.currentTarget.style.transform = 'scale(1.05)'
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.background = 'linear-gradient(to right, rgba(59,194,208,0.85), rgba(43,168,181,0.85))'
          e.currentTarget.style.boxShadow = '0 10px 15px -3px rgba(59,194,208,0.25), 0 4px 6px -4px rgba(59,194,208,0.15)'
          e.currentTarget.style.transform = 'scale(1)'
        }}
        style={{
          position: 'fixed',
          bottom: '16px',
          [wizardSide]: '16px',
          zIndex: 50,
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          padding: '10px 18px',
          borderRadius: '9999px',
          border: 'none',
          background: 'linear-gradient(to right, rgba(59,194,208,0.85), rgba(43,168,181,0.85))',
          color: '#fff',
          textShadow: '2px 2px 1px #000',
          boxShadow: '0 10px 15px -3px rgba(59,194,208,0.25), 0 4px 6px -4px rgba(59,194,208,0.15)',
          cursor: 'pointer',
          transition: 'all 0.2s ease',
          backdropFilter: 'blur(8px)',
        }}
        title={t('Installation Wizard')}
        type="button"
      >
        <Sparkles style={{ width: '16px', height: '16px' }} />
        <span style={{ fontSize: '14px', fontWeight: 500 }}>{t('Installation Wizard')}</span>
        <span style={{ fontSize: '12px', opacity: 0.8 }}>{realCompletedCount}/{realSteps.length}</span>
      </button>
    )
  }

  // Start phase: show a simple welcome panel with a "start" button
  if (isStartPhase) {
    return (
      <div
        style={{
          position: 'fixed',
          bottom: '16px',
          [wizardSide]: '16px',
          zIndex: 50,
          width: '360px',
          maxWidth: 'calc(100vw - 2rem)',
          overflow: 'hidden',
          borderRadius: '16px',
          backgroundColor: '#fff',
          boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.03)',
        }}
      dir={getDirection()}
    >
        {/* Gradient header */}
        <div style={{ padding: '20px', background: 'linear-gradient(135deg, rgba(59,194,208,0.08), rgba(43,168,181,0.03))' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <div
                style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '12px',
                  background: 'linear-gradient(135deg, #3BC2D0, #2BA8B5)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  boxShadow: '0 2px 4px rgba(59,194,208,0.3)',
                }}
              >
                <Sparkles style={{ width: '20px', height: '20px', color: '#fff' }} />
              </div>
              <div>
                <div style={{ fontSize: '16px', fontWeight: 700, color: '#111827' }}>{t('Installation Wizard')}</div>
                <div style={{ fontSize: '12px', color: '#9CA3AF', marginTop: '2px' }}>BoostBot</div>
              </div>
            </div>

            <button
              onClick={() => setIsMinimized(true)}
              style={{ width: '32px', height: '32px', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'none', background: 'transparent', cursor: 'pointer' }}
              title={t('Minimize')}
              type="button"
            >
              <Minus style={{ width: '16px', height: '16px', color: '#9CA3AF' }} />
            </button>
          </div>

          <p style={{ fontSize: '14px', color: '#4B5563', lineHeight: 1.6, margin: 0 }}>
            {sprintf(t('Welcome! Let\'s set up your bot in %d simple steps.'), realSteps.length)}
          </p>
        </div>

        {/* Start button */}
        <div style={{ padding: '16px 20px' }}>
          <button
            onClick={() => { markStepCompleted('start'); goToStep(1) }}
            style={{
              width: '100%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '8px',
              padding: '12px 20px',
              borderRadius: '12px',
              border: 'none',
              background: 'linear-gradient(135deg, #3BC2D0, #2BA8B5)',
              color: '#fff',
              fontSize: '15px',
              fontWeight: 600,
              cursor: 'pointer',
              boxShadow: '0 4px 12px rgba(59,194,208,0.35)',
              transition: 'all 0.2s ease',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.boxShadow = '0 6px 20px rgba(59,194,208,0.45)'
              e.currentTarget.style.transform = 'translateY(-1px)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.boxShadow = '0 4px 12px rgba(59,194,208,0.35)'
              e.currentTarget.style.transform = 'translateY(0)'
            }}
            type="button"
          >
            <Rocket style={{ width: '18px', height: '18px' }} />
            {t('Start Installation')}
          </button>
        </div>
      </div>
    )
  }

  return (
    <div
      style={{
        position: 'fixed',
        bottom: '16px',
        [wizardSide]: '16px',
        zIndex: 50,
        width: '360px',
        maxWidth: 'calc(100vw - 2rem)',
        maxHeight: 'calc(100vh - 2rem)',
        overflow: 'hidden',
        borderRadius: '16px',
        backgroundColor: '#fff',
        boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.03)',
        display: 'flex',
        flexDirection: 'column',
      }}
      dir={getDirection()}
    >
      {/* Header with gradient accent */}
      <div style={{ flexShrink: 0, background: 'linear-gradient(to left, rgba(59,194,208,0.05), transparent)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '12px 16px' }}>
          {/* Step badge — display real step number (excluding start step) */}
          <div
            style={{
              flexShrink: 0,
              width: '40px',
              height: '40px',
              borderRadius: '12px',
              background: 'linear-gradient(135deg, #3BC2D0, #2BA8B5)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
            }}
          >
            <span style={{ color: '#fff', fontSize: '14px', fontWeight: 700 }}>{currentStepIndex}</span>
          </div>

          {/* Step info */}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: '14px', fontWeight: 600, color: '#111827', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {currentStep?.name}
            </div>
            <div style={{ fontSize: '12px', color: '#9CA3AF', marginTop: '2px' }}>
              {sprintf(t('Step %1$d of %2$d · %3$d completed'), currentStepIndex, realSteps.length, realCompletedCount)}
            </div>
          </div>

          {/* Action buttons */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <WizardHelpButton />

            <button
              onClick={toggleExpanded}
              style={{ width: '32px', height: '32px', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'none', background: 'transparent', cursor: 'pointer' }}
              className="hover:bg-gray-100"
              title={isExpanded ? t('Collapse list') : t('Show all steps')}
              type="button"
            >
              {isExpanded
                ? <ChevronUp className="w-4 h-4 text-gray-400" />
                : <ChevronDown className="w-4 h-4 text-gray-400" />
              }
            </button>

            <button
              onClick={() => setIsMinimized(true)}
              style={{ width: '32px', height: '32px', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'none', background: 'transparent', cursor: 'pointer' }}
              className="hover:bg-gray-100"
              title={t('Minimize')}
              type="button"
            >
              <Minus className="w-4 h-4 text-gray-400" />
            </button>
          </div>
        </div>

        {/* Progress bar */}
        <div style={{ padding: '0 16px 12px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <div style={{ flex: 1, height: '6px', backgroundColor: '#F3F4F6', borderRadius: '9999px', overflow: 'hidden' }}>
              <div
                style={{
                  height: '100%',
                  width: `${progressPercent}%`,
                  background: 'linear-gradient(to left, #3BC2D0, #2BA8B5)',
                  borderRadius: '9999px',
                  transition: 'width 0.7s ease-out',
                }}
              />
            </div>
            <span style={{ fontSize: '12px', fontWeight: 500, color: '#3BC2D0', fontVariantNumeric: 'tabular-nums' }}>{progressPercent}%</span>
          </div>
        </div>
      </div>

      {/* Expanded step list — excludes the "start" step */}
      {isExpanded && (
        <div style={{ borderTop: '1px solid #F3F4F6', flexShrink: 1, minHeight: 0, overflow: 'hidden' }}>
          <WizardStepList
            steps={realSteps}
            currentStepIndex={currentStepIndex - 1}
            progress={progress}
            onStepClick={(index) => goToStep(index + 1)}
          />
        </div>
      )}

      {/* Streaming message */}
      {streamingMessage && (
        <div style={{ padding: '12px 16px', borderTop: '1px solid #F9FAFB', flexShrink: 0 }}>
          <WizardStreamingMessage message={streamingMessage} isStreaming={isStreaming} />
        </div>
      )}

      {/* Navigation footer */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderTop: '1px solid #F3F4F6', backgroundColor: 'rgba(249,250,251,0.5)', flexShrink: 0 }}>
        {/* Prev / Next arrows */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
          <button
            onClick={goToPrevStep}
            disabled={isFirstStep}
            style={{
              width: '32px',
              height: '32px',
              borderRadius: '8px',
              backgroundColor: '#fff',
              border: '1px solid #E5E7EB',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: isFirstStep ? 'not-allowed' : 'pointer',
              opacity: isFirstStep ? 0.3 : 1,
            }}
            title={t('Previous')}
            type="button"
          >
            <ChevronRight className="w-4 h-4 text-gray-600" />
          </button>

          <button
            onClick={goToNextStep}
            disabled={isLastStep}
            style={{
              width: '32px',
              height: '32px',
              borderRadius: '8px',
              backgroundColor: '#fff',
              border: '1px solid #E5E7EB',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: isLastStep ? 'not-allowed' : 'pointer',
              opacity: isLastStep ? 0.3 : 1,
            }}
            title={t('Next')}
            type="button"
          >
            <ChevronLeft className="w-4 h-4 text-gray-600" />
          </button>

          {/* Settings cog */}
          <button
            onClick={() => panelNavigate('/settings')}
            style={{
              width: '32px',
              height: '32px',
              borderRadius: '8px',
              backgroundColor: '#fff',
              border: '1px solid #E5E7EB',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
            }}
            className="hover:bg-gray-100"
            title={t('Settings')}
            type="button"
          >
            <Settings className="w-4 h-4 text-gray-600" />
          </button>

          {/* Re-ping */}
          <button
            onClick={() => {
              if (currentStep) {
                const targets = STEP_PING_TARGETS[currentStep.id]
                if (targets) executePingTargetsInstant(targets)
              }
            }}
            style={{
              width: '32px',
              height: '32px',
              borderRadius: '8px',
              backgroundColor: '#fff',
              border: '1px solid #E5E7EB',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
            }}
            className="hover:bg-gray-100"
            title={t('Highlight relevant area')}
            type="button"
          >
            <LocateFixed className="w-4 h-4 text-gray-600" />
          </button>
        </div>

        {/* Skip button */}
        {!isLastStep && (
          <button
            onClick={skipStep}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              padding: '6px 12px',
              borderRadius: '8px',
              fontSize: '14px',
              fontWeight: 500,
              border: 'none',
              background: 'transparent',
              color: currentStep?.isCritical ? '#D97706' : '#6B7280',
              cursor: 'pointer',
            }}
            className={currentStep?.isCritical ? 'hover:bg-amber-50' : 'hover:bg-gray-100'}
            title={currentStep?.isCritical ? t('Important step — not recommended to skip') : t('Skip this step')}
            type="button"
          >
            <SkipForward className="w-3.5 h-3.5" />
            {t('Skip')}
          </button>
        )}

        {/* Finish button */}
        {isLastStep && (
          <button
            onClick={() => wizard.completeWizard()}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              padding: '8px 16px',
              borderRadius: '8px',
              fontSize: '14px',
              fontWeight: 600,
              background: 'linear-gradient(to right, #3BC2D0, #2BA8B5)',
              color: '#fff',
              border: 'none',
              cursor: 'pointer',
              boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
            }}
            type="button"
          >
            <Sparkles className="w-4 h-4" />
            {t('Finish Installation')}
          </button>
        )}
      </div>
    </div>
  )
}
