import { useState } from 'react'
import guardpotImg from '../assets/guardpot.jpeg'
import './GuardpotTour.css'

type TourStep = {
  id: string
  title: string
  description: string
  region: { leftPct: number; topPct: number; widthPct: number; heightPct: number }
  popupPosition?: { leftPct?: number; topPct?: number; rightPct?: number; bottomPct?: number }
}

const guardpotSteps: TourStep[] = [
  {
    id: 'overview',
    title: 'Guardpot Overview',
    description: 'Guardpot yönetim sayfasına hoş geldiniz! Bu sayfada tüm Guardpot agentlarınızı görüntüleyebilir, yönetebilir ve yeni agentlar ekleyebilirsiniz.',
    region: { leftPct: 0, topPct: 0, widthPct: 100, heightPct: 100 },
    popupPosition: { rightPct: 35, topPct: 55 },
  },
  {
    id: 'guardpot-card',
    title: 'Guardpot-Local Card',
    description: 'Bu kart mevcut Guardpot\'unuzun detaylarını gösterir. IP adresi, işletim sistemi ve son aktivite bilgilerini burada görebilirsiniz.',
    region: { leftPct: 15, topPct: 3, widthPct: 41, heightPct: 20 },
    popupPosition: { rightPct: 61, topPct: 24 },
  },
  {
    id: 'action-buttons',
    title: 'Action Buttons',
    description: 'Bu butonlar ile yeni Guardpot ekleyebilir, kurulum kılavuzunu görüntüleyebilir ve Guardpot havuzunu yönetebilirsiniz.',
    region: { leftPct: 58, topPct: 3, widthPct: 40, heightPct: 21 },
    popupPosition: { leftPct: 75, topPct: 25 },
  },
  {
    id: 'guardpot-list',
    title: 'Guardpot List',
    description: 'Tüm Guardpot agentlarınızın listesi burada görüntülenir. Durum, konum, IP adresi ve işlem butonları ile agentlarınızı yönetebilirsiniz.',
    region: { leftPct: 15, topPct: 25, widthPct: 83, heightPct: 60 },
    popupPosition: { leftPct: 17, bottomPct: 18 },
  },
]

type GuardpotTourProps = {
  autoStart?: boolean
  onClose?: () => void
}

export default function GuardpotTour({ autoStart = false, onClose }: GuardpotTourProps) {
  const [isModalOpen, setIsModalOpen] = useState(autoStart)
  const [currentStep, setCurrentStep] = useState(0)
  const [isTransitioning, setIsTransitioning] = useState(false)
  const [isModalAnimating, setIsModalAnimating] = useState(false)
  const [transitionDirection, setTransitionDirection] = useState<'next' | 'prev'>('next')

  const handleStartTour = () => {
    setIsModalOpen(true)
    setCurrentStep(0)
  }

  const handleClose = () => {
    setIsModalAnimating(true)
    // Parent'ı hemen bilgilendir
    if (onClose) {
      onClose()
    }
    setTimeout(() => {
      setIsModalOpen(false)
      setCurrentStep(0)
      setIsTransitioning(false)
      setTimeout(() => {
        setIsModalAnimating(false)
      }, 50)
    }, 250)
  }

  const handleNext = () => {
    if (currentStep < guardpotSteps.length - 1) {
      setTransitionDirection('next')
      setIsTransitioning(true)
      setTimeout(() => {
        setCurrentStep(currentStep + 1)
        setIsTransitioning(false)
      }, 500)
    }
  }

  const handlePrevious = () => {
    if (currentStep > 0) {
      setTransitionDirection('prev')
      setIsTransitioning(true)
      setTimeout(() => {
        setCurrentStep(currentStep - 1)
        setIsTransitioning(false)
      }, 500)
    }
  }

  const handleStepClick = (stepIndex: number) => {
    if (stepIndex !== currentStep) {
      setTransitionDirection(stepIndex > currentStep ? 'next' : 'prev')
      setIsTransitioning(true)
      setTimeout(() => {
        setCurrentStep(stepIndex)
        setIsTransitioning(false)
      }, 500)
    }
  }

  const activeStep = guardpotSteps[currentStep]

  return (
    <>
      {/* Main Preview - only show if not autoStart */}
      {!autoStart && (
        <div className="guardpot-preview-container">
          <img 
            className="guardpot-preview-image"
            src={guardpotImg} 
            alt="Guardpot Management" 
          />
          
          <div className="guardpot-preview-overlay">
            <button 
              className="guardpot-start-button"
              onClick={handleStartTour}
            >
              Start Guardpot Tour
            </button>
          </div>
        </div>
      )}

      {/* Modal */}
      {isModalOpen && (
        <>
        <div 
          className={`guardpot-modal-backdrop ${isModalAnimating ? 'closing' : ''}`}
          onClick={handleClose}
        >
          <div 
            className={`guardpot-modal-content ${isModalAnimating ? 'closing' : ''}`}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="guardpot-modal-image-wrapper">
              <img 
                className="guardpot-modal-image"
                src={guardpotImg} 
                alt="Guardpot Management" 
              />

            {/* Dark overlay with highlight window - only show if not first step */}
            {currentStep > 0 && (
              <>
                {/* Top overlay */}
                {activeStep.region.topPct > 0 && (
                  <div 
                    className={`guardpot-overlay-top ${isTransitioning ? 'guardpot-overlay-transitioning' : ''}`}
                    style={{
                      height: `${activeStep.region.topPct}%`
                    }}
                  />
                )}

                {/* Left overlay */}
                {activeStep.region.leftPct > 0 && (
                  <div
                    className={`guardpot-overlay-left ${isTransitioning ? 'guardpot-overlay-transitioning' : ''}`}
                    style={{ top: `${activeStep.region.topPct}%`, width: `${activeStep.region.leftPct}%`, height: `${activeStep.region.heightPct}%` }}
                  />
                )}

                {/* Right overlay */}
                {activeStep.region.leftPct + activeStep.region.widthPct < 100 && (
                  <div
                    className={`guardpot-overlay-right ${isTransitioning ? 'guardpot-overlay-transitioning' : ''}`}
                    style={{ top: `${activeStep.region.topPct}%`, left: `${activeStep.region.leftPct + activeStep.region.widthPct}%`, height: `${activeStep.region.heightPct}%` }}
                  />
                )}

                {/* Bottom overlay */}
                {activeStep.region.topPct + activeStep.region.heightPct < 100 && (
                  <div
                    className={`guardpot-overlay-bottom ${isTransitioning ? 'guardpot-overlay-transitioning' : ''}`}
                    style={{ top: `${activeStep.region.topPct + activeStep.region.heightPct}%` }}
                  />
                )}

                {/* Highlight border */}
                <div
                  className={`guardpot-highlight-border ${isTransitioning ? 'transitioning' : ''}`}
                  style={{ left: `${activeStep.region.leftPct}%`, top: `${activeStep.region.topPct}%`, width: `${activeStep.region.widthPct}%`, height: `${activeStep.region.heightPct}%` }}
                />
              </>
            )}

            {/* Step info popup */}
            <div 
              className={`guardpot-step-popup ${isTransitioning ? `transitioning transition-${transitionDirection}` : ''} ${isModalAnimating ? 'closing' : ''}`}
              style={{ 
                ...(activeStep.popupPosition?.leftPct && { left: `${activeStep.popupPosition.leftPct}%` }), 
                ...(activeStep.popupPosition?.topPct && { top: `${activeStep.popupPosition.topPct}%` }), 
                ...(activeStep.popupPosition?.rightPct && { right: `${activeStep.popupPosition.rightPct}%` }), 
                ...(activeStep.popupPosition?.bottomPct && { bottom: `${activeStep.popupPosition.bottomPct}%` }), 
              }} 
            >
              {/* Subtle animated border */}
              <div className="guardpot-popup-animated-border" />
              
              {/* Quit button */}
              <button className="guardpot-quit-button" onClick={handleClose}>×</button>

              {/* Content with higher z-index */}
              <div className="guardpot-popup-content">
                <div style={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  gap: '12px', 
                  marginBottom: '12px' 
                }}>
                  <div style={{ 
                    background: '#b02f34', 
                    color: 'white', 
                    fontSize: '12px', 
                    padding: '4px 8px', 
                    borderRadius: '999px', 
                    fontWeight: '600' 
                  }}>
                    {currentStep + 1} / {guardpotSteps.length}
                  </div>
                  <h3 style={{ 
                    margin: 0, 
                    fontWeight: '600', 
                    fontSize: '1.1rem' 
                  }}>
                    {activeStep.title}
                  </h3>
                </div>
                <p style={{ 
                  margin: '0 0 16px 0', 
                  color: '#b9bfca', 
                  lineHeight: '1.5' 
                }}>
                  {activeStep.description}
                </p>

                <div style={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'space-between', 
                  gap: '12px' 
                }}>
                  <button 
                    style={{ 
                      padding: '8px 16px', 
                      borderRadius: '8px', 
                      border: '1px solid #2a2f39', 
                      background: '#171a21', 
                      color: '#f1f2f5', 
                      cursor: 'pointer', 
                      fontSize: '14px', 
                      opacity: currentStep === 0 ? 0.5 : 1 
                    }} 
                    onClick={handlePrevious} 
                    disabled={currentStep === 0}
                  >
                    Previous
                  </button>

                  {currentStep === guardpotSteps.length - 1 ? (
                    <button 
                      style={{ 
                        padding: '8px 16px', 
                        borderRadius: '8px', 
                        border: '1px solid #8e262a', 
                        background: '#b02f34', 
                        color: 'white', 
                        cursor: 'pointer', 
                        fontSize: '14px' 
                      }} 
                      onClick={handleClose}
                    >
                      Finish
                    </button>
                  ) : (
                    <button 
                      style={{ 
                        padding: '8px 16px', 
                        borderRadius: '8px', 
                        border: '1px solid #8e262a', 
                        background: '#b02f34', 
                        color: 'white', 
                        cursor: 'pointer', 
                        fontSize: '14px' 
                      }} 
                      onClick={handleNext}
                    >
                      Next
                    </button>
                  )}
                </div>
              </div>
            </div>
            </div>
          </div>
        </div>

        {/* Progress Bar - only show when modal is open */}
        {!isModalAnimating && (
          <div className={`guardpot-tour-progress-bar ${isModalAnimating ? 'closing' : ''}`}>
            {guardpotSteps.map((step, index) => (
              <div
                key={step.id}
                className={`guardpot-progress-segment ${index < currentStep ? 'completed' : ''} ${index === currentStep ? 'active' : ''}`}
                onClick={() => handleStepClick(index)}
                title={step.title}
              >
                <div className="guardpot-progress-segment-fill" />
                <div className={`guardpot-progress-step-number ${index < currentStep ? 'completed' : ''} ${index === currentStep ? 'active' : ''}`}>
                  {index + 1}
                </div>
              </div>
            ))}
          </div>
        )}
        </>
      )}

      {/* CSS Animations */}
      <style>{`
        @keyframes pulseGlow {
          0% { box-shadow: 0 0 0 0 rgba(176, 47, 52, 0.4); }
          50% { box-shadow: 0 0 8px 4px rgba(176, 47, 52, 0.6); }
          100% { box-shadow: 0 0 0 0 rgba(176, 47, 52, 0.4); }
        }
      `}</style>
    </>
  )
}
