import { useState, useEffect } from 'react'
import { X, ArrowLeft, ArrowRight } from 'lucide-react'
import { useLanguage } from '../i18n/LanguageContext'

const getTutorialSteps = (t) => [
  {
    target: '[data-tutorial="dashboard"]',
    title: t('tutorial.dashboard.title'),
    description: t('tutorial.dashboard.desc'),
    position: 'right',
  },
  {
    target: '[data-tutorial="campaigns"]',
    title: t('tutorial.campaigns.title'),
    description: t('tutorial.campaigns.desc'),
    position: 'right',
  },
  {
    target: '[data-tutorial="posts"]',
    title: t('tutorial.posts.title'),
    description: t('tutorial.posts.desc'),
    position: 'right',
  },
  {
    target: '[data-tutorial="tasks"]',
    title: t('tutorial.tasks.title'),
    description: t('tutorial.tasks.desc'),
    position: 'right',
  },
  {
    target: '[data-tutorial="team"]',
    title: t('tutorial.team.title'),
    description: t('tutorial.team.desc'),
    position: 'right',
  },
  {
    target: '[data-tutorial="assets"]',
    title: t('tutorial.assets.title'),
    description: t('tutorial.assets.desc'),
    position: 'right',
  },
  {
    target: '[data-tutorial="new-post"]',
    title: t('tutorial.newPost.title'),
    description: t('tutorial.newPost.desc'),
    position: 'bottom',
  },
  {
    target: '[data-tutorial="filters"]',
    title: t('tutorial.filters.title'),
    description: t('tutorial.filters.desc'),
    position: 'bottom',
  },
]

export default function Tutorial({ onComplete }) {
  const { t } = useLanguage()
  const [currentStep, setCurrentStep] = useState(0)
  const [targetRect, setTargetRect] = useState(null)
  const [tooltipPosition, setTooltipPosition] = useState({ top: 0, left: 0 })

  const TUTORIAL_STEPS = getTutorialSteps(t)
  const step = TUTORIAL_STEPS[currentStep]

  useEffect(() => {
    updatePosition()
    window.addEventListener('resize', updatePosition)
    return () => window.removeEventListener('resize', updatePosition)
  }, [currentStep])

  const updatePosition = () => {
    const target = document.querySelector(step.target)
    if (!target) {
      console.warn(`Tutorial target not found: ${step.target}`)
      return
    }

    const rect = target.getBoundingClientRect()
    setTargetRect(rect)

    // Calculate tooltip position
    const tooltipWidth = 360
    const tooltipHeight = 200
    const padding = 20

    let top = rect.top
    let left = rect.right + padding

    // Adjust based on position hint
    if (step.position === 'bottom') {
      top = rect.bottom + padding
      left = rect.left
    } else if (step.position === 'left') {
      top = rect.top
      left = rect.left - tooltipWidth - padding
    } else if (step.position === 'top') {
      top = rect.top - tooltipHeight - padding
      left = rect.left
    }

    // Keep tooltip on screen
    if (left + tooltipWidth > window.innerWidth) {
      left = rect.left - tooltipWidth - padding
    }
    if (left < 0) {
      left = padding
    }
    if (top + tooltipHeight > window.innerHeight) {
      top = window.innerHeight - tooltipHeight - padding
    }
    if (top < 0) {
      top = padding
    }

    setTooltipPosition({ top, left })
  }

  const handleNext = () => {
    if (currentStep < TUTORIAL_STEPS.length - 1) {
      setCurrentStep(currentStep + 1)
    } else {
      onComplete()
    }
  }

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

  const handleSkip = () => {
    onComplete()
  }

  if (!targetRect) return null

  return (
    <div className="fixed inset-0 z-[9999] pointer-events-none">
      {/* Dark overlay with spotlight cutout */}
      <svg className="absolute inset-0 w-full h-full pointer-events-auto" style={{ pointerEvents: 'auto' }}>
        <defs>
          <mask id="tutorial-mask">
            <rect x="0" y="0" width="100%" height="100%" fill="white" />
            <rect
              x={targetRect.left - 4}
              y={targetRect.top - 4}
              width={targetRect.width + 8}
              height={targetRect.height + 8}
              rx="8"
              fill="black"
            />
          </mask>
        </defs>
        <rect
          x="0"
          y="0"
          width="100%"
          height="100%"
          fill="rgba(0, 0, 0, 0.7)"
          mask="url(#tutorial-mask)"
          onClick={handleSkip}
          style={{ cursor: 'pointer' }}
        />
      </svg>

      {/* Highlight ring around target */}
      <div
        className="absolute border-4 border-brand-primary rounded-lg shadow-lg transition-all duration-300 pointer-events-none"
        style={{
          top: targetRect.top - 4,
          left: targetRect.left - 4,
          width: targetRect.width + 8,
          height: targetRect.height + 8,
        }}
      />

      {/* Tooltip card */}
      <div
        className="absolute bg-white rounded-xl shadow-2xl border border-border p-6 animate-fade-in pointer-events-auto"
        style={{
          top: tooltipPosition.top,
          left: tooltipPosition.left,
          width: 360,
          maxWidth: 'calc(100vw - 40px)',
        }}
      >
        {/* Close button */}
        <button
          onClick={handleSkip}
          className="absolute top-4 right-4 text-text-tertiary hover:text-text-primary transition-colors"
        >
          <X className="w-5 h-5" />
        </button>

        {/* Content */}
        <div className="space-y-4">
          <div>
            <div className="flex items-center gap-2 text-xs font-medium text-brand-primary mb-2">
              <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-brand-primary/10 text-brand-primary text-xs font-bold">
                {currentStep + 1}
              </span>
              <span>{t('tutorial.step')} {currentStep + 1} {t('tutorial.of')} {TUTORIAL_STEPS.length}</span>
            </div>
            <h3 className="text-xl font-bold text-text-primary mb-2">{step.title}</h3>
            <p className="text-sm text-text-secondary leading-relaxed">{step.description}</p>
          </div>

          {/* Progress bar */}
          <div className="w-full h-1.5 bg-surface-tertiary rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-brand-primary to-purple-500 transition-all duration-300"
              style={{ width: `${((currentStep + 1) / TUTORIAL_STEPS.length) * 100}%` }}
            />
          </div>

          {/* Navigation */}
          <div className="flex items-center justify-between gap-3 pt-2">
            <button
              onClick={handleSkip}
              className="text-sm font-medium text-text-tertiary hover:text-text-primary transition-colors"
            >
              {t('tutorial.skip')}
            </button>
            <div className="flex items-center gap-2">
              {currentStep > 0 && (
                <button
                  onClick={handlePrev}
                  className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-text-secondary hover:bg-surface-tertiary rounded-lg transition-colors"
                >
                  <ArrowLeft className="w-4 h-4" />
                  {t('tutorial.prev')}
                </button>
              )}
              <button
                onClick={handleNext}
                className="flex items-center gap-1.5 px-5 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light shadow-sm transition-colors"
              >
                {currentStep < TUTORIAL_STEPS.length - 1 ? t('tutorial.next') : t('tutorial.finish')}
                {currentStep < TUTORIAL_STEPS.length - 1 && <ArrowRight className="w-4 h-4" />}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
