import { useState } from 'react'
import secureLink1 from '../assets/securelink1.png'
import secureLink2 from '../assets/securelink2.png'
import secureLink3 from '../assets/securelink3.png'
import './SecureLinkTour.css'

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

const secureLinkSteps: TourStep[] = [
  {
    id: 'overview',
    title: 'Secure Link Overview',
    description: 'Secure Link sayfasına hoş geldiniz! Bu sayfada Guardpot\'lar arasındaki ağ performansını ve bağlantı doğrulamasını görüntüleyebilirsiniz.',
    image: secureLink1,
    region: { leftPct: 0, topPct: 0, widthPct: 100, heightPct: 100 },
    popupPosition: { rightPct: 3, topPct: 5 },
  },
  {
    id: 'network-topology',
    title: 'Network Topology',
    description: 'Bu interaktif ağ topolojisi haritası, tüm Guardpot bağlantılarınızı görsel olarak gösterir. Her düğüm bir Guardpot\'u temsil eder.',
    image: secureLink1,
    region: { leftPct: 15, topPct: 1, widthPct: 83, heightPct: 10 },
    popupPosition: { rightPct: 3, topPct: 13 },
  },
  {
    id: 'network-stats',
    title: 'Network Statistics',
    description: 'Üst kısımda ağınızın sağlık durumunu gösteren istatistikler bulunur. Healthy, Errors, Running ve Total bağlantı sayılarını buradan takip edebilirsiniz.',
    image: secureLink1,
    region: { leftPct: 15, topPct: 14, widthPct: 84, heightPct: 75 },
    popupPosition: { rightPct: 70, topPct: 23 },
  },
  {
    id: 'connection-details',
    title: 'Connection Details',
    description: 'Bağlantılar arasında tıklayarak detaylı ping, jitter ve paket kaybı istatistiklerini görüntüleyebilirsiniz. Grafikler gerçek zamanlı performansı gösterir.',
    image: secureLink2,
    region: { leftPct: 19, topPct: 1, widthPct: 74, heightPct: 93 },
    popupPosition: { leftPct: 2, topPct: 14 },
  },
  {
    id: 'navigation-controls',
    title: 'Navigation Controls',
    description: 'Sol alt köşedeki kontroller ile ağ haritasını döndürebilir, yakınlaştırabilir ve istediğiniz açıdan görüntüleyebilirsiniz.',
    image: secureLink1,
    region: { leftPct: 92, topPct: 42, widthPct: 8, heightPct: 15 },
    popupPosition: { leftPct: 62, bottomPct: 45 },
  },
  {
    id: 'graph-view',
    title: 'Graph View Options',
    description: 'Sağ üst köşede Graph, Link Checks ve List seçenekleri ile görünümü özelleştirebilirsiniz. Her görünüm farklı perspektifler sunar.',
    image: secureLink3,
    region: { leftPct: 28, topPct: 5, widthPct: 44, heightPct: 90 },
    popupPosition: { leftPct: 72, topPct: 14 },
  },
]

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

export default function SecureLinkTour({ autoStart = false, onClose }: SecureLinkTourProps) {
  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 < secureLinkSteps.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 = secureLinkSteps[currentStep]

  if (!autoStart && !isModalOpen) {
    return (
      <div className="secure-link-tour-container">
        <div className="secure-link-preview-section">
          <div className="secure-link-preview-image-wrapper">
            <img src={secureLink1} alt="Secure Link Preview" className="secure-link-preview-image" />
            <div className="secure-link-preview-overlay">
              <button className="start-tour-button" onClick={handleStartTour}>
                <span className="button-icon">▶</span>
                Start Secure Link Tour
              </button>
            </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <>
      <div className={`secure-link-modal-backdrop ${isModalAnimating ? 'closing' : ''}`} onClick={handleClose}>
        <div className={`secure-link-modal-content ${isModalAnimating ? 'closing' : ''}`} onClick={(e) => e.stopPropagation()}>
          <div className="secure-link-modal-image-wrapper">
            <img className="secure-link-modal-image" src={activeStep.image} alt="Secure Link" />

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

                {/* Left overlay */}
                {activeStep.region.leftPct > 0 && (
                  <div
                    className={`secure-link-overlay-left ${isTransitioning ? 'secure-link-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={`secure-link-overlay-right ${isTransitioning ? 'secure-link-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={`secure-link-overlay-bottom ${isTransitioning ? 'secure-link-overlay-transitioning' : ''}`}
                    style={{ top: `${activeStep.region.topPct + activeStep.region.heightPct}%` }}
                  />
                )}

                {/* Highlight border */}
                <div
                  className={`secure-link-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={`secure-link-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="secure-link-popup-animated-border" />
              
              {/* Quit button */}
              <button className="secure-link-quit-button" onClick={handleClose}>×</button>

              {/* Content with higher z-index */}
              <div className="secure-link-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}/{secureLinkSteps.length}
                  </div>
                  <h3 style={{ 
                    margin: 0, 
                    fontSize: '18px', 
                    fontWeight: 600, 
                    color: '#f1f2f5' 
                  }}>
                    {activeStep.title}
                  </h3>
                </div>
                <p style={{ 
                  margin: 0, 
                  fontSize: '14px', 
                  lineHeight: 1.6, 
                  color: '#b9bfca' 
                }}>
                  {activeStep.description}
                </p>
                <div style={{ 
                  display: 'flex', 
                  gap: '10px', 
                  marginTop: '20px', 
                  justifyContent: 'space-between', 
                  alignItems: 'center' 
                }}>
                  <button
                    onClick={handlePrevious}
                    disabled={currentStep === 0}
                    style={{
                      background: currentStep === 0 ? 'rgba(0, 0, 0, 0.3)' : '#1a1d26',
                      border: '1px solid #262a33',
                      color: currentStep === 0 ? '#555' : '#b9bfca',
                      padding: '8px 16px',
                      borderRadius: '6px',
                      cursor: currentStep === 0 ? 'not-allowed' : 'pointer',
                      fontSize: '14px',
                      fontWeight: 500,
                      transition: 'all 200ms ease'
                    }}
                    onMouseEnter={(e) => {
                      if (currentStep !== 0) {
                        e.currentTarget.style.background = '#262a33'
                        e.currentTarget.style.color = '#f1f2f5'
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (currentStep !== 0) {
                        e.currentTarget.style.background = '#1a1d26'
                        e.currentTarget.style.color = '#b9bfca'
                      }
                    }}
                  >
                    ← Previous
                  </button>
                  <button
                    onClick={currentStep === secureLinkSteps.length - 1 ? handleClose : handleNext}
                    style={{
                      background: 'linear-gradient(135deg, #b02f34 0%, #8a252a 100%)',
                      border: '1px solid #b02f34',
                      color: 'white',
                      padding: '8px 20px',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      fontWeight: 600,
                      transition: 'all 200ms ease'
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = 'linear-gradient(135deg, #c93640 0%, #b02f34 100%)'
                      e.currentTarget.style.transform = 'translateY(-1px)'
                      e.currentTarget.style.boxShadow = '0 4px 12px rgba(176, 47, 52, 0.4)'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = 'linear-gradient(135deg, #b02f34 0%, #8a252a 100%)'
                      e.currentTarget.style.transform = 'translateY(0)'
                      e.currentTarget.style.boxShadow = 'none'
                    }}
                  >
                    {currentStep === secureLinkSteps.length - 1 ? 'Finish' : 'Next →'}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Progress Bar */}
      <div className={`secure-link-tour-progress-bar ${isModalAnimating ? 'closing' : ''}`}>
        {secureLinkSteps.map((step, index) => (
          <div
            key={step.id}
            className={`secure-link-progress-segment ${index < currentStep ? 'completed' : ''} ${index === currentStep ? 'active' : ''}`}
            onClick={() => handleStepClick(index)}
            title={step.title}
          >
            <div className="secure-link-progress-segment-fill" />
            <div className={`secure-link-progress-step-number ${index < currentStep ? 'completed' : ''} ${index === currentStep ? 'active' : ''}`}>
              {index + 1}
            </div>
          </div>
        ))}
      </div>
    </>
  )
}

