import { useState } from 'react'
import attackSurface1 from '../assets/attacksurface1.png'
import attackSurface2 from '../assets/attacksurface2.png'
import attackSurface3 from '../assets/attacksurface3.png'
import './AttackSurfaceTour.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 attackSurfaceSteps: TourStep[] = [
  {
    id: 'overview',
    title: 'Attack Surface Overview',
    description: 'Attack Surface sayfasına hoş geldiniz! Bu sayfada sisteminizdeki potansiyel saldırı yüzeylerini analiz edebilir ve güvenlik açıklarını tespit edebilirsiniz.',
    image: attackSurface1,
    region: { leftPct: 0, topPct: 0, widthPct: 100, heightPct: 100 },
    popupPosition: { rightPct: 31, topPct: 25 },
  },
  {
    id: 'network-visualization',
    title: 'Network Visualization',
    description: 'Bu bölümde ağınızın görsel haritasını görebilirsiniz. Bağlantılar ve nodlar arasındaki ilişkileri kolayca takip edebilirsiniz.',
    image: attackSurface1,
    region: { leftPct: 15, topPct: 2, widthPct: 82, heightPct: 12 },
    popupPosition: { rightPct: 3, topPct: 16 },
  },
  {
    id: 'asset-list',
    title: 'Asset List',
    description: 'Sisteminizdeki tüm varlıkların listesi burada görüntülenir. Her bir varlığın detaylarına bu bölümden erişebilirsiniz.',
    image: attackSurface1,
    region: { leftPct: 15, topPct: 16, widthPct: 83, heightPct: 80 },
    popupPosition: { leftPct: 17, bottomPct: 59 },
  },
  {
    id: 'detailed-analysis',
    title: 'Detailed Analysis View',
    description: 'Şimdi detaylı analiz ekranına geçiyoruz. Bu ekranda seçili varlığınız hakkında daha kapsamlı bilgilere ulaşabilirsiniz.',
    image: attackSurface2,
    region: { leftPct: 14, topPct: 0, widthPct: 85, heightPct: 100 },
    popupPosition: { rightPct: 3, topPct:4 },
  },
  {
    id: 'vulnerability-score',
    title: 'Vulnerability Score',
    description: 'Üst bölümde varlığınızın risk skorunu ve güvenlik durumunu görebilirsiniz. Kritik bulgular burada vurgulanır.',
    image: attackSurface2,
    region: { leftPct: 15, topPct: 16, widthPct: 83, heightPct: 10 },
    popupPosition: { rightPct: 60, topPct: 28 },
  },
  {
    id: 'threat-details',
    title: 'Threat Details',
    description: 'Bu bölümde tespit edilen tehditlerin detayları yer alır. Her bir tehdidin öncelik seviyesi ve açıklamasını inceleyebilirsiniz.',
    image: attackSurface2,
    region: { leftPct: 15, topPct: 30, widthPct: 84, heightPct: 70 },
    popupPosition: { leftPct: 17, topPct: 75 },
  },
  {
    id: 'mitigation-actions',
    title: 'Mitigation Actions',
    description: 'Sağ tarafta tehditleri azaltmak için önerilen aksiyonlar listelenir. Bu önerileri uygulayarak güvenliğinizi artırabilirsiniz.',
    image: attackSurface2,
    region: { leftPct: 92, topPct: 39, widthPct: 8, heightPct: 20 },
    popupPosition: { rightPct: 10, topPct: 39 },
  },

  {
    id: 'global-threat-map',
    title: 'Global Threat Map',
    description: 'Son olarak, global tehdit haritasını görüntülüyoruz. Bu haritada dünyanın farklı bölgelerinden gelen tehditleri ve saldırı paternlerini takip edebilirsiniz.',
    image: attackSurface3,
    region: { leftPct: 28, topPct: 6, widthPct: 44, heightPct: 88 },
    popupPosition: { rightPct: 2, topPct: 10 },
  },
]

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

export default function AttackSurfaceTour({ autoStart = false, onClose }: AttackSurfaceTourProps) {
  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 < attackSurfaceSteps.length - 1) {
      setTransitionDirection('next')
      setIsTransitioning(true)
      // Allow slide-out, then change step, keep transitioning for a tick to slide-in
      setTimeout(() => {
        setCurrentStep(currentStep + 1)
        setTimeout(() => {
          setIsTransitioning(false)
        }, 50)
      }, 300)
    }
  }

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

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

  const activeStep = attackSurfaceSteps[currentStep]

  return (
    <>
      {/* Main Preview - only show if not autoStart */}
      {!autoStart && (
        <div className="attack-surface-preview-container">
          <img 
            className="attack-surface-preview-image"
            src={attackSurface1} 
            alt="Attack Surface Analysis" 
          />
          
          <div className="attack-surface-preview-overlay">
            <button 
              className="attack-surface-start-button"
              onClick={handleStartTour}
            >
              Start Attack Surface Tour
            </button>
          </div>
        </div>
      )}

      {/* Modal */}
      {isModalOpen && (
        <>
        <div 
          className={`attack-surface-modal-backdrop ${isModalAnimating ? 'closing' : ''}`}
          onClick={handleClose}
        >
          <div 
            className={`attack-surface-modal-content ${isModalAnimating ? 'closing' : ''}`}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="attack-surface-modal-image-wrapper">
              <img 
                className="attack-surface-modal-image"
                src={activeStep.image} 
                alt="Attack Surface Analysis" 
              />

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

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

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

              {/* Content with higher z-index */}
              <div className="attack-surface-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} / {attackSurfaceSteps.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 === attackSurfaceSteps.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={`attack-surface-tour-progress-bar ${isModalAnimating ? 'closing' : ''}`}>
            {attackSurfaceSteps.map((step, index) => (
              <div
                key={step.id}
                className={`attack-surface-progress-segment ${index < currentStep ? 'completed' : ''} ${index === currentStep ? 'active' : ''}`}
                onClick={() => handleStepClick(index)}
                title={step.title}
              >
                <div className="attack-surface-progress-segment-fill" />
                <div className={`attack-surface-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>
    </>
  )
}

