import { useState, useEffect, useRef } from "react";
import { X, ChevronLeft, ChevronRight, SkipForward } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useOnboarding } from "./onboarding-provider";

interface OnboardingTooltipProps {
  className?: string;
}

export function OnboardingTooltip({ className }: OnboardingTooltipProps) {
  const {
    isActive,
    currentStep,
    steps,
    nextStep,
    prevStep,
    skipStep,
    endOnboarding,
    markStepCompleted,
  } = useOnboarding();

  const [position, setPosition] = useState({ top: 0, left: 0 });
  const tooltipRef = useRef<HTMLDivElement>(null);

  const currentStepData = steps[currentStep];

  useEffect(() => {
    if (!isActive || !currentStepData) {
      return;
    }

    const updatePosition = () => {
      const targetElement = document.querySelector(currentStepData.target);
      
      if (targetElement && tooltipRef.current) {
        const targetRect = targetElement.getBoundingClientRect();
        const tooltipRect = tooltipRef.current.getBoundingClientRect();
        
        let top = 0;
        let left = 0;

        switch (currentStepData.position) {
          case "top":
            top = targetRect.top - tooltipRect.height - 10;
            left = targetRect.left + (targetRect.width - tooltipRect.width) / 2;
            break;
          case "bottom":
            top = targetRect.bottom + 10;
            left = targetRect.left + (targetRect.width - tooltipRect.width) / 2;
            break;
          case "left":
            top = targetRect.top + (targetRect.height - tooltipRect.height) / 2;
            left = targetRect.left - tooltipRect.width - 10;
            break;
          case "right":
            top = targetRect.top + (targetRect.height - tooltipRect.height) / 2;
            left = targetRect.right + 10;
            break;
          default:
            top = targetRect.bottom + 10;
            left = targetRect.left + (targetRect.width - tooltipRect.width) / 2;
        }

        // Ensure tooltip stays within viewport
        const padding = 10;
        top = Math.max(padding, Math.min(window.innerHeight - tooltipRect.height - padding, top));
        left = Math.max(padding, Math.min(window.innerWidth - tooltipRect.width - padding, left));

        setPosition({ top, left });

        // Add highlight to target element
        targetElement.classList.add("onboarding-highlight");
        
        // Scroll target into view if needed
        targetElement.scrollIntoView({
          behavior: "smooth",
          block: "center",
          inline: "center",
        });
      }
    };

    // Delay positioning to ensure DOM is ready
    const timeoutId = setTimeout(updatePosition, 200);
    
    // Update position on resize
    window.addEventListener("resize", updatePosition);
    
    return () => {
      clearTimeout(timeoutId);
      window.removeEventListener("resize", updatePosition);
      
      // Remove highlight from all elements
      document.querySelectorAll(".onboarding-highlight").forEach(el => {
        el.classList.remove("onboarding-highlight");
      });
    };
  }, [isActive, currentStep, currentStepData]);

  const handleNext = () => {
    if (currentStepData) {
      markStepCompleted(currentStepData.id);
    }
    nextStep();
  };

  const handleSkip = () => {
    skipStep();
  };

  const handleEnd = () => {
    endOnboarding();
  };

  if (!isActive || !currentStepData) {
    return null;
  }

  return (
    <>
      {/* Overlay */}
      <div className="fixed inset-0 bg-black/20 backdrop-blur-sm z-40" />
      
      {/* Tooltip */}
      <Card
        ref={tooltipRef}
        className={`fixed z-50 w-80 shadow-lg border-primary/20 ${className}`}
        style={{
          top: position.top,
          left: position.left,
        }}
      >
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <CardTitle className="text-lg">{currentStepData.title}</CardTitle>
              {currentStepData.optional && (
                <Badge variant="secondary" className="text-xs">
                  Optional
                </Badge>
              )}
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleEnd}
              className="h-6 w-6 p-0"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <span>{currentStep + 1} of {steps.length}</span>
            <div className="flex-1 bg-muted rounded-full h-1">
              <div
                className="bg-primary h-1 rounded-full transition-all duration-300"
                style={{ width: `${((currentStep + 1) / steps.length) * 100}%` }}
              />
            </div>
          </div>
        </CardHeader>
        
        <CardContent className="pt-0">
          <p className="text-sm text-muted-foreground mb-3">
            {currentStepData.description}
          </p>
          
          <div className="text-sm mb-4">
            {currentStepData.content}
          </div>
          
          <div className="flex items-center justify-between gap-2">
            <div className="flex gap-1">
              {currentStep > 0 && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={prevStep}
                  className="h-8"
                >
                  <ChevronLeft className="h-3 w-3 mr-1" />
                  Back
                </Button>
              )}
              
              {currentStepData.optional && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleSkip}
                  className="h-8"
                >
                  <SkipForward className="h-3 w-3 mr-1" />
                  Skip
                </Button>
              )}
            </div>
            
            <Button
              size="sm"
              onClick={handleNext}
              className="h-8"
            >
              {currentStepData.action || (currentStep === steps.length - 1 ? "Finish" : "Next")}
              {currentStep < steps.length - 1 && (
                <ChevronRight className="h-3 w-3 ml-1" />
              )}
            </Button>
          </div>
        </CardContent>
      </Card>
    </>
  );
}