import React, { useState, useEffect } from 'react';
import { X, ChevronRight } from 'lucide-react';

type TourStep = {
  selector: string;
  title: string;
  body: string;
};

const TOUR_STEPS: TourStep[] = [
  {
    selector: '[data-tour="welcome"]',
    title: 'Willkommen bei EmberClone',
    body: 'Hier hast du den vollen Überblick über deine Projekte und deine investierte Zeit.',
  },
  {
    selector: '[data-tour="nav-customers"]',
    title: 'Kunden verwalten',
    body: 'Lege hier deine Kunden an, um Projekte sauber zuordnen und später abzurechnen.',
  },
  {
    selector: '[data-tour="nav-time"]',
    title: 'Zeit erfassen',
    body: 'Hier kannst du deine täglichen Einträge erstellen, bearbeiten und exportieren.',
  },
  {
    selector: '[data-tour="search-hint"]',
    title: 'Schnellsuche',
    body: 'Nutze ⌘K (oder Strg+K), um blitzschnell durch deine Projekte zu navigieren.',
  },
];

export default function OnboardingTour() {
  const [currentStep, setCurrentStep] = useState<number | null>(null);
  const [coords, setCoords] = useState({ top: 0, left: 0, width: 0, height: 0 });
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const isDone = localStorage.getItem('onboarding-done');
    if (!isDone) {
      setCurrentStep(0);
    }
  }, []);

  useEffect(() => {
    if (currentStep === null) return;

    const updatePosition = () => {
      const element = document.querySelector(TOUR_STEPS[currentStep].selector);
      if (element) {
        const rect = element.getBoundingClientRect();
        setCoords({
          top: rect.top,
          left: rect.left,
          width: rect.width,
          height: rect.height,
        });
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

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

  const handleNext = () => {
    if (currentStep === null) return;
    if (currentStep < TOUR_STEPS.length - 1) {
      setCurrentStep(currentStep + 1);
    } else {
      completeTour();
    }
  };

  const completeTour = () => {
    localStorage.setItem('onboarding-done', 'true');
    setCurrentStep(null);
  };

  if (currentStep === null || !isVisible) return null;

  const step = TOUR_STEPS[currentStep];
  const isLastStep = currentStep === TOUR_STEPS.length - 1;

  return (
    <div className="fixed inset-0 z-[100] pointer-events-auto overflow-hidden">
      {/* Backdrop with Hole */}
      <div 
        className="absolute inset-0 bg-black/50 transition-all duration-300 ease-in-out"
        style={{
          clipPath: `polygon(
            0% 0%, 0% 100%, 
            ${coords.left}px 100%, 
            ${coords.left}px ${coords.top}px, 
            ${coords.left + coords.width}px ${coords.top}px, 
            ${coords.left + coords.width}px ${coords.top + coords.height}px, 
            ${coords.left}px ${coords.top + coords.height}px, 
            ${coords.left}px 100%, 
            100% 100%, 100% 0%
          )`
        }}
      />

      {/* Popover Card */}
      <div 
        className="absolute bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-xl shadow-2xl p-5 w-80 transition-all duration-300 animate-in fade-in zoom-in-95"
        style={{
          top: coords.top + coords.height > window.innerHeight - 250 
            ? coords.top - 220 
            : coords.top + coords.height + 16,
          left: Math.max(16, Math.min(window.innerWidth - 336, coords.left + (coords.width / 2) - 160))
        }}
      >
        <div className="flex justify-between items-start mb-2">
          <h3 className="font-semibold text-zinc-900 dark:text-zinc-100">{step.title}</h3>
          <button 
            onClick={completeTour}
            className="p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-md transition-colors"
            title="Tour überspringen"
          >
            <X className="w-4 h-4 text-zinc-500" />
          </button>
        </div>
        
        <p className="text-sm text-zinc-600 dark:text-zinc-400 mb-6 leading-relaxed">
          {step.body}
        </p>

        <div className="flex justify-between items-center">
          <button 
            onClick={completeTour}
            className="text-xs font-medium text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300 transition-colors"
          >
            Überspringen
          </button>
          
          <button 
            onClick={handleNext}
            className="flex items-center gap-1 px-3 py-1.5 bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity"
          >
            {isLastStep ? 'Verstanden' : 'Weiter'}
            {!isLastStep && <ChevronRight className="w-3.5 h-3.5" />}
          </button>
        </div>

        <div className="mt-4 flex justify-center gap-1">
          {TOUR_STEPS.map((_, idx) => (
            <div 
              key={idx} 
              className={`h-1 rounded-full transition-all duration-300 ${
                idx === currentStep ? 'w-4 bg-zinc-900 dark:bg-zinc-100' : 'w-1 bg-zinc-200 dark:bg-zinc-700'
              }`} 
            />
          ))}
        </div>
      </div>
    </div>
  );
}