import { useState } from 'react'
import dashboardImg from '../assets/dashboard.jpeg'
import guardpotImg from '../assets/guardpot.jpeg'
import attackSurfaceImg from '../assets/attacksurface1.png'
import secureLinkImg from '../assets/securelink1.png'
import vgnImg from '../assets/virtualguardednetwork1.png'
import GuardpotTour from './GuardpotTour'
import AttackSurfaceTour from './AttackSurfaceTour'
import SecureLinkTour from './SecureLinkTour'
import VirtualGuardedNetworkTour from './VirtualGuardedNetworkTour'
import './DashboardTour.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 dashboardSteps: TourStep[] = [
  {
    id: 'overview',
    title: 'Dashboard Overview',
    description: "Guardpot Dashboard'a hoş geldiniz! Bu genel bakış ekranında sistem durumunuzu, aktif bağlantıları ve güvenlik metriklerinizi görebilirsiniz.",
    region: { leftPct: 0, topPct: 0, widthPct: 100, heightPct: 100 },
    popupPosition: { rightPct: 1, topPct: 25 },
  },
  {
    id: 'navigation-menu',
    title: 'Navigation Menu',
    description: 'Sol taraftaki menü ile Dashboard, Guardpots, Attack Surface gibi farklı bölümlere erişebilirsiniz. Şu anda Dashboard bölümündesiniz.',
    region: { leftPct: 32, topPct: 1, widthPct: 67, heightPct: 76 },
    popupPosition: { rightPct: 70, topPct: 20 },
  },
  {
    id: 'network-graph',
    title: 'Network Graph',
    description: 'Ana network grafiği ile sistem durumunuzu görsel olarak takip edebilirsiniz. Merkezi "G" noktasından dünya çapındaki bağlantılarınızı görebilirsiniz.',
    region: { leftPct: 15, topPct: 77, widthPct: 83, heightPct: 20 },
    popupPosition: { rightPct: 5, bottomPct: 25 },
  },
]

type TourOption = { id: string; name: string; description: string; disabled?: boolean }
const tourOptions: TourOption[] = [
  { id: 'dashboard', name: 'Dashboard', description: 'Dashboard overview and features' },
  { id: 'guardpot', name: 'Guardpot', description: 'Guardpot management system' },
  { id: 'attack-surface', name: 'Attack Surface', description: 'Attack surface analysis' },
  { id: 'secure-link', name: 'Secure Link', description: 'Secure link management' },
  { id: 'virtual-guarded-network', name: 'Virtual Guarded Network', description: 'Virtual network configuration' }
]

export default function DashboardTour() {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [currentStep, setCurrentStep] = useState(0)
  const [isTransitioning, setIsTransitioning] = useState(false)
  const [isModalAnimating, setIsModalAnimating] = useState(false)
  const [selectedTour, setSelectedTour] = useState('dashboard')
  const [isClosing, setIsClosing] = useState(false)
  const [transitionDirection, setTransitionDirection] = useState<'next' | 'prev'>('next')

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

  const handleClose = () => {
    setIsModalAnimating(true)
    setIsClosing(true)
    setTimeout(() => {
      setIsModalOpen(false)
      setCurrentStep(0)
      setIsTransitioning(false)
      setTimeout(() => {
        setIsModalAnimating(false)
        setIsClosing(false)
      }, 50)
    }, 250)
  }

  const handleNext = () => {
    if (currentStep < dashboardSteps.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 = dashboardSteps[currentStep]

  return (
    <>
      {/* Main Container - hide when modal is open */}
      {!isModalOpen && !isClosing && (
      <div className="dashboard-tour-container">
        {/* Tour Selection Menu */}
        <div className="tour-selection-menu">
          <h3 className="tour-selection-title">Select Tour</h3>
          <div className="tour-options-container">
            {tourOptions.map((option) => (
              <button
                key={option.id}
                className={`tour-option-button ${selectedTour === option.id ? 'selected' : ''} ${option.disabled ? 'disabled' : ''}`}
                onClick={() => !option.disabled && setSelectedTour(option.id)}
                disabled={option.disabled}
              >
                <div className="tour-option-content">
                  <div className="tour-option-title">{option.name}</div>
                  <div className="tour-option-description">{option.description}</div>
                </div>
                {option.disabled && <span className="disabled-badge">Soon</span>}
              </button>
            ))}
          </div>
        </div>

        {/* Main Preview */}
        <div className="main-preview-container">
          <div className="preview-image-container">
            <img 
              className="preview-image" 
              src={
                selectedTour === 'dashboard' ? dashboardImg :
                selectedTour === 'guardpot' ? guardpotImg :
                selectedTour === 'attack-surface' ? attackSurfaceImg :
                selectedTour === 'secure-link' ? secureLinkImg :
                selectedTour === 'virtual-guarded-network' ? vgnImg :
                dashboardImg
              }
              alt={
                selectedTour === 'dashboard' ? 'Guardpot Dashboard' : 
                selectedTour === 'guardpot' ? 'Guardpot Management' : 
                selectedTour === 'attack-surface' ? 'Attack Surface' :
                selectedTour === 'secure-link' ? 'Secure Link' :
                selectedTour === 'virtual-guarded-network' ? 'Virtual Guarded Network' :
                'Tour Preview'
              } 
            />
            <div className="preview-overlay">
              <button className="start-tour-button" onClick={handleStartTour}>
                <span className="start-icon">▶</span>
                {selectedTour === 'dashboard' && 'Start Dashboard Tour'}
                {selectedTour === 'guardpot' && 'Start Guardpot Tour'}
                {selectedTour === 'attack-surface' && 'Start Attack Surface Tour'}
                {selectedTour === 'secure-link' && 'Start Secure Link Tour'}
                {selectedTour === 'virtual-guarded-network' && 'Start VGN Tour'}
                {!selectedTour && 'Select a Tour'}
              </button>
            </div>
          </div>
        </div>
      </div>
      )}

      {/* Modals for all tours */}
      {(isModalOpen || isClosing) && selectedTour === 'guardpot' && (
        <div className="tour-modal-container">
          <GuardpotTour autoStart={true} onClose={handleClose} />
        </div>
      )}

      {(isModalOpen || isClosing) && selectedTour === 'attack-surface' && (
        <div className="tour-modal-container">
          <AttackSurfaceTour autoStart={true} onClose={handleClose} />
        </div>
      )}

      {(isModalOpen || isClosing) && selectedTour === 'secure-link' && (
        <div className="tour-modal-container">
          <SecureLinkTour autoStart={true} onClose={handleClose} />
        </div>
      )}

      {(isModalOpen || isClosing) && selectedTour === 'virtual-guarded-network' && (
        <div className="tour-modal-container">
          <VirtualGuardedNetworkTour autoStart={true} onClose={handleClose} />
        </div>
      )}

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

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

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

                {/* Highlight border */}
                <div
                  className={`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={`step-info-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}%` }),
              }}
            >
              <div className="popup-animated-border" />

              <button className="quit-button" onClick={handleClose}>×</button>

              <div className="popup-content">
                <div className="popup-header">
                  <div className="step-counter">{currentStep + 1} / {dashboardSteps.length}</div>
                  <h3 className="popup-title">{activeStep.title}</h3>
                </div>
                <p className="popup-description">{activeStep.description}</p>

                <div className="popup-navigation">
                  <button className={`nav-button ${currentStep === 0 ? 'disabled' : ''}`} onClick={handlePrevious} disabled={currentStep === 0}>
                    Previous
                  </button>

                  {currentStep === dashboardSteps.length - 1 ? (
                    <button className="nav-button primary" onClick={handleClose}>Finish</button>
                  ) : (
                    <button className="nav-button primary" onClick={handleNext}>Next</button>
                  )}
                </div>
              </div>
            </div>
            </div>
          </div>
        </div>

        {/* Progress Bar – identical behavior to other tours */}
        {!isModalAnimating && (
          <div className={`dashboard-progress-bar ${isModalAnimating ? 'closing' : ''}`}>
            {dashboardSteps.map((step, index) => (
              <div
                key={step.id}
                className={`dashboard-progress-segment ${index < currentStep ? 'completed' : ''} ${index === currentStep ? 'active' : ''}`}
                onClick={() => handleStepClick(index)}
                title={step.title}
              >
                <div className="dashboard-progress-segment-fill" />
                <div className={`dashboard-progress-step-number ${index < currentStep ? 'completed' : ''} ${index === currentStep ? 'active' : ''}`}>
                  {index + 1}
                </div>
              </div>
            ))}
          </div>
        )}
        </>
      )}
    </>
  )
}


