import { useState, useEffect, useCallback } from 'react';
import { router } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { X, ChevronLeft, ChevronRight, CheckCircle2 } from 'lucide-react';
import { cn } from '@/lib/utils';

export type TutorialStep = {
  title: string;
  description: string;
  route?: string;
  selector?: string;
  sidebarItem?: string;
  position?: 'top' | 'bottom' | 'left' | 'right';
};

type TutorialOverlayProps = {
  steps: TutorialStep[];
  title: string;
  onClose: () => void;
};

const TutorialOverlay = ({ steps, title, onClose }: TutorialOverlayProps) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [highlightRect, setHighlightRect] = useState<DOMRect | null>(null);
  const [tooltipPos, setTooltipPos] = useState<{ top: number; left: number } | null>(null);
  const step = steps[currentStep];
  const isLastStep = currentStep === steps.length - 1;

  const findAndHighlight = useCallback(() => {
    if (!step) return;

    // Navigate to route if needed
    if (step.route) {
      router.visit(step.route);
    }

    // Wait for DOM to settle after navigation
    setTimeout(() => {
      let el: Element | null = null;

      if (step.selector) {
        el = document.querySelector(step.selector);
      } else if (step.sidebarItem) {
        // Find sidebar item by text
        const links = document.querySelectorAll("[data-sidebar='menu-button']");
        links.forEach((link) => {
          if (link.textContent?.trim().includes(step.sidebarItem!)) {
            el = link;
          }
        });
      }

      if (el) {
        const rect = el.getBoundingClientRect();
        setHighlightRect(rect);

        // Calculate tooltip position
        const pos = step.position || 'bottom';
        let top = 0;
        let left = 0;
        const tooltipWidth = 380;
        const tooltipHeight = 200;

        switch (pos) {
          case 'bottom':
            top = rect.bottom + 12;
            left = Math.max(16, Math.min(rect.left, window.innerWidth - tooltipWidth - 16));
            break;
          case 'top':
            top = rect.top - tooltipHeight - 12;
            left = Math.max(16, Math.min(rect.left, window.innerWidth - tooltipWidth - 16));
            break;
          case 'right':
            top = rect.top;
            left = rect.right + 12;
            break;
          case 'left':
            top = rect.top;
            left = rect.left - tooltipWidth - 12;
            break;
        }

        // Keep tooltip in viewport
        top = Math.max(16, Math.min(top, window.innerHeight - tooltipHeight - 16));
        left = Math.max(16, Math.min(left, window.innerWidth - tooltipWidth - 16));

        setTooltipPos({ top, left });

        // Scroll element into view
        el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      } else {
        setHighlightRect(null);
        setTooltipPos({ top: window.innerHeight / 2 - 100, left: window.innerWidth / 2 - 190 });
      }
    }, 300);
  }, [step]);

  useEffect(() => {
    findAndHighlight();
    window.addEventListener('resize', findAndHighlight);
    return () => window.removeEventListener('resize', findAndHighlight);
  }, [findAndHighlight]);

  const goNext = () => {
    if (isLastStep) {
      onClose();
    } else {
      setCurrentStep((s) => s + 1);
    }
  };

  const goPrev = () => {
    if (currentStep > 0) setCurrentStep((s) => s - 1);
  };

  // Keyboard navigation
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight' || e.key === 'Enter') goNext();
      if (e.key === 'ArrowLeft') goPrev();
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [currentStep, isLastStep]);

  const padding = 6;

  return (
    <div className="fixed inset-0 z-[9999]">
      {/* Dark overlay with spotlight cutout */}
      <svg className="absolute inset-0 w-full h-full" style={{ pointerEvents: 'none' }}>
        <defs>
          <mask id="tutorial-spotlight">
            <rect x="0" y="0" width="100%" height="100%" fill="white" />
            {highlightRect && (
              <rect
                x={highlightRect.left - padding}
                y={highlightRect.top - padding}
                width={highlightRect.width + padding * 2}
                height={highlightRect.height + padding * 2}
                rx="8"
                fill="black"
              />
            )}
          </mask>
        </defs>
        <rect
          x="0"
          y="0"
          width="100%"
          height="100%"
          fill="rgba(0,0,0,0.6)"
          mask="url(#tutorial-spotlight)"
        />
      </svg>

      {/* Highlight border */}
      {highlightRect && (
        <div
          className="absolute border-2 border-primary rounded-lg animate-pulse pointer-events-none"
          style={{
            top: highlightRect.top - padding,
            left: highlightRect.left - padding,
            width: highlightRect.width + padding * 2,
            height: highlightRect.height + padding * 2,
          }}
        />
      )}

      {/* Click-through blocker (prevents clicking on the page) */}
      <div className="absolute inset-0" onClick={(e) => e.stopPropagation()} />

      {/* Tooltip card */}
      {tooltipPos && (
        <div
          className="absolute bg-background border border-border rounded-xl shadow-2xl p-5 animate-fade-in"
          style={{
            top: tooltipPos.top,
            left: tooltipPos.left,
            width: 380,
            zIndex: 10000,
          }}
        >
          {/* Header */}
          <div className="flex items-center justify-between mb-3">
            <Badge variant="secondary" className="text-xs">
              Step {currentStep + 1} of {steps.length}
            </Badge>
            <Button variant="ghost" size="icon" className="h-6 w-6" onClick={onClose}>
              <X className="h-4 w-4" />
            </Button>
          </div>

          {/* Title bar */}
          <div className="text-xs text-muted-foreground mb-1 truncate">{title}</div>

          {/* Step content */}
          <h3 className="font-semibold text-foreground mb-2">{step.title}</h3>
          <p className="text-sm text-muted-foreground leading-relaxed">{step.description}</p>

          {/* Progress bar */}
          <div className="flex gap-1 my-4">
            {steps.map((_, i) => (
              <div
                key={i}
                className={cn(
                  'h-1 flex-1 rounded-full transition-colors',
                  i <= currentStep ? 'bg-primary' : 'bg-muted',
                )}
              />
            ))}
          </div>

          {/* Navigation */}
          <div className="flex items-center justify-between">
            <Button
              variant="ghost"
              size="sm"
              onClick={goPrev}
              disabled={currentStep === 0}
              className="gap-1"
            >
              <ChevronLeft className="h-4 w-4" /> Previous
            </Button>
            <Button size="sm" onClick={goNext} className="gap-1">
              {isLastStep ? (
                <>
                  <CheckCircle2 className="h-4 w-4" /> Complete
                </>
              ) : (
                <>
                  Next <ChevronRight className="h-4 w-4" />
                </>
              )}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

// Tutorial step definitions mapped to SOP procedures
export const tutorialStepMap: Record<string, TutorialStep[]> = {
  'view-orders': [
    { title: 'Open Orders', description: "Click 'Orders' in the sidebar to navigate to the orders management page.", sidebarItem: 'Orders', route: '/admin/orders', position: 'right' },
    { title: 'Search Orders', description: 'Use the search bar at the top to filter orders by customer name, email, or order ID.', selector: "input[placeholder*='Search']", route: '/admin/orders', position: 'bottom' },
    { title: 'Filter by Status', description: 'Use the status filter dropdown to show only specific order statuses like Pending, Paid, Confirmed, Cancelled, or Refunded.', selector: "button[role='combobox']", route: '/admin/orders', position: 'bottom' },
    { title: 'View Order Details', description: 'Click the expand arrow on any order row to view full details including delegates, venue, and trainer information.', selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
  ],
  'assign-trainer-venue': [
    { title: 'Go to Orders', description: 'Navigate to the Orders page from the sidebar.', sidebarItem: 'Orders', route: '/admin/orders', position: 'right' },
    { title: 'Expand an Order', description: 'Click on an order row to expand it and reveal the assignment controls.', selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
    { title: 'Assign Trainer & Venue', description: 'Select a trainer from the Trainer dropdown and a venue from the Venue dropdown. Only trainers assigned to the course will appear.', selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
    { title: 'Save Changes', description: "Click 'Save Changes' to update the order with the assigned trainer and venue.", selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
  ],
  'process-refund': [
    { title: 'Open Orders', description: 'Navigate to Orders from the sidebar.', sidebarItem: 'Orders', route: '/admin/orders', position: 'right' },
    { title: 'Expand the Order', description: 'Click on the order you want to refund to expand its details.', selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
    { title: 'Click Refund', description: "Click the 'Refund' button in the expanded order details to open the refund dialog.", selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
    { title: 'Process the Refund', description: "Enter the refund amount (partial or full), provide a reason, and click 'Process Refund'. For Stripe payments, the refund is processed automatically.", selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
  ],
  'create-company': [
    { title: 'Open Companies', description: "Click 'Companies' in the sidebar to navigate to company management.", sidebarItem: 'Companies', route: '/admin/companies', position: 'right' },
    { title: 'Add New Company', description: "Click the 'Add Company' button to open the creation form.", selector: 'button:has(> svg)', route: '/admin/companies', position: 'bottom' },
    { title: 'Fill Company Details', description: 'Enter the company name, registration number, VAT number, contact details, and address. Set the company type, payment terms, and credit limit.', selector: 'form', route: '/admin/companies', position: 'bottom' },
  ],
  'manage-credit': [
    { title: 'Navigate to Companies', description: "Click 'Companies' in the sidebar.", sidebarItem: 'Companies', route: '/admin/companies', position: 'right' },
    { title: 'Select a Company', description: 'Click on a company name in the table to view its detail page.', selector: 'table tbody tr:first-child', route: '/admin/companies', position: 'bottom' },
    { title: 'Go to Credit Tab', description: "Click the 'Credit' tab to view and manage the company's credit limit and available credit.", selector: "[role='tablist']", route: '/admin/companies', position: 'bottom' },
  ],
  'add-trainer': [
    { title: 'Open Trainers', description: "Click 'Trainers' in the sidebar to navigate to trainer management.", sidebarItem: 'Trainers', route: '/admin/trainers', position: 'right' },
    { title: 'Add Trainer', description: "Click the 'Add Trainer' button and fill in the trainer's first name, last name, email, phone, and any notes.", selector: 'button:has(> svg)', route: '/admin/trainers', position: 'bottom' },
  ],
  'manage-availability': [
    { title: 'Open Availability', description: "Click 'Availability' in the sidebar to navigate to the availability management page.", sidebarItem: 'Availability', route: '/admin/availability', position: 'right' },
    { title: 'Select Trainer', description: 'Select a trainer from the dropdown to view their weekly availability pattern.', selector: "button[role='combobox']", route: '/admin/availability', position: 'bottom' },
    { title: 'Set Weekly Schedule', description: "Toggle days on/off to set the default weekly availability pattern. Use 'Add Override' for specific date exceptions.", selector: 'table', route: '/admin/availability', position: 'bottom' },
  ],
  'create-course': [
    { title: 'Open Courses', description: "Click 'Courses' in the sidebar to navigate to course management.", sidebarItem: 'Courses', route: '/admin/courses', position: 'right' },
    { title: 'Add Course', description: "Click 'Add Course' to open the course creation form.", selector: "a[href='/admin/courses/new']", route: '/admin/courses', position: 'bottom' },
    { title: 'Fill Course Details', description: 'Enter the title, category, slug, price, duration, capacity, description, and other fields. Upload a course image and toggle Featured/Active settings.', selector: 'form', route: '/admin/courses/new', position: 'bottom' },
  ],
  'assign-trainers-course': [
    { title: 'Open Course Assignments', description: "Click 'Course Assignments' in the sidebar.", sidebarItem: 'Course Assignments', route: '/admin/course-assignments', position: 'right' },
    { title: 'Assign Trainer', description: "Select a course, then select a trainer and optionally a default venue. Click 'Assign' to link them.", selector: 'form', route: '/admin/course-assignments', position: 'bottom' },
  ],
  'create-venue': [
    { title: 'Open Venues', description: "Click 'Venues' in the sidebar to navigate to venue management.", sidebarItem: 'Venues', route: '/admin/venues', position: 'right' },
    { title: 'Add Venue', description: "Click 'Add Venue' and enter the name, address, city, postcode, country, and capacity.", selector: 'button:has(> svg)', route: '/admin/venues', position: 'bottom' },
  ],
  'create-discount': [
    { title: 'Open Discount Codes', description: "Click 'Discount Codes' in the sidebar.", sidebarItem: 'Discount Codes', route: '/admin/discount-codes', position: 'right' },
    { title: 'Add Discount Code', description: "Click 'Add Discount Code' and configure the code, type (% or £), value, scope (General/Company/User), max uses, and validity dates.", selector: 'button:has(> svg)', route: '/admin/discount-codes', position: 'bottom' },
  ],
  'assign-role': [
    { title: 'Open User Roles', description: "Click 'User Roles' in the sidebar.", sidebarItem: 'User Roles', route: '/admin/user-roles', position: 'right' },
    { title: 'Assign a Role', description: "Enter the user's email, select a role, optionally select a company for company-scoped roles, and click 'Assign Role'.", selector: 'form', route: '/admin/user-roles', position: 'bottom' },
  ],
  'invite-user': [
    { title: 'Open User Roles', description: "Click 'User Roles' in the sidebar.", sidebarItem: 'User Roles', route: '/admin/user-roles', position: 'right' },
    { title: 'Switch to Invite Tab', description: "Click the 'Invite New User' tab to access the invitation form.", selector: "[role='tablist']", route: '/admin/user-roles', position: 'bottom' },
    { title: 'Send Invitation', description: "Enter the new user's email, full name, select a role, and click 'Send Invite'. They'll receive an email to set up their account.", selector: 'form', route: '/admin/user-roles', position: 'bottom' },
  ],
  'view-calendar': [
    { title: 'Open Training Calendar', description: "Click 'Training Calendar' in the sidebar.", sidebarItem: 'Training Calendar', route: '/admin/calendar', position: 'right' },
    { title: 'Browse the Calendar', description: 'Use the month/week toggle to change views. Click on bookings to see details including course, trainer, venue, and delegates.', selector: ".fc, table, [class*='calendar']", route: '/admin/calendar', position: 'bottom' },
  ],
  'pre-course-form': [
    { title: 'Go to Orders', description: 'Navigate to Orders from the sidebar. Pre-course forms (TD-02) are automatically sent when a booking is completed.', sidebarItem: 'Orders', route: '/admin/orders', position: 'right' },
    { title: 'Resend if Needed', description: "Expand an order and click 'Resend Pre-Course Form' to re-issue the TD-02 questionnaire to all delegates.", selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
  ],
  'on-day-checkin': [
    { title: 'Go to Orders', description: 'Navigate to Orders. The on-the-day check-in starts with generating a QR code from the order.', sidebarItem: 'Orders', route: '/admin/orders', position: 'right' },
    { title: 'Generate QR Code', description: "Expand an order and click the 'QR Code' button to generate a scannable code for delegates to use at the venue.", selector: 'table tbody tr:first-child', route: '/admin/orders', position: 'bottom' },
  ],
  'booking-flow': [
    { title: 'Public Course Page', description: "Delegates browse courses on the public website and click 'Book Now' to start the checkout process.", route: '/courses', selector: 'main', position: 'bottom' },
    { title: 'Complete Booking', description: 'After selecting dates, entering delegate details, and completing payment, a confirmation page shows booking details, joining instructions, and PPE requirements.', route: '/courses', selector: 'main', position: 'bottom' },
  ],
};

export default TutorialOverlay;
