'use client';

import { useMemo } from 'react';
import { X } from 'lucide-react';
import { cn } from '@djangocfg/ui-core/lib';
import {
  Popover,
  PopoverAnchor,
  PopoverContent,
  PopoverArrow,
  Button,
} from '@djangocfg/ui-core/components';
import { TourProgress } from './TourProgress';
import { TourNavigation } from './TourNavigation';
import type { TourContentProps, TourPosition } from '../types';

/**
 * Map TourPosition to Radix Popover side.
 */
function mapPositionToSide(
  position: TourPosition | undefined
): 'top' | 'bottom' | 'left' | 'right' {
  if (!position || position === 'auto') return 'bottom';
  return position;
}

/**
 * Tour step content popover.
 * Uses Radix Popover with virtual anchor for positioning.
 */
export function TourContent({
  step,
  targetRect,
  currentIndex,
  totalSteps,
  onNext,
  onPrevious,
  onClose,
  progressVariant = 'dots',
  showSkipButton = true,
  showArrow = false,
  skipLabel,
  finishLabel,
  onGoTo,
  className,
}: TourContentProps) {
  // Prepare virtual ref for Popover anchor
  const virtualRef = useMemo(
    () => ({
      current: {
        getBoundingClientRect: () => targetRect,
      },
    }),
    [targetRect]
  );

  // Prepare positioning
  const side = mapPositionToSide(step.position);
  const sideOffset = step.offset ?? 12;
  const align = step.align ?? 'center';
  const alignOffset = step.alignOffset ?? 0;

  // Prepare step state
  const isFirstStep = currentIndex === 0;
  const isLastStep = currentIndex === totalSteps - 1;

  // Prepare styles
  const popoverContentClassName = cn('z-[51] w-72', step.className, className);

  // Prepare custom actions
  const hasCustomActions = step.actions && step.actions.length > 0;
  const customActions = useMemo(() => {
    if (!step.actions) return [];

    return step.actions.map((action, index) => ({
      key: index,
      label: action.label,
      onClick: action.onClick,
      className: cn(
        'text-sm font-medium underline-offset-4 hover:underline',
        action.variant === 'destructive' && 'text-destructive'
      ),
    }));
  }, [step.actions]);

  // Event handlers
  const preventAutoFocus = (e: Event) => e.preventDefault();

  return (
    <Popover open>
      <PopoverAnchor virtualRef={virtualRef as React.RefObject<Element>} />
      <PopoverContent
        side={side}
        sideOffset={sideOffset}
        align={align}
        alignOffset={alignOffset}
        avoidCollisions
        collisionPadding={16}
        className={popoverContentClassName}
        onOpenAutoFocus={preventAutoFocus}
        onCloseAutoFocus={preventAutoFocus}
        role="dialog"
        aria-labelledby="tour-title"
        aria-describedby="tour-description"
      >
        {showArrow && <PopoverArrow className="fill-popover" />}

        {/* Header with close button */}
        <div className="flex items-start justify-between gap-2 pb-2">
          <h3 id="tour-title" className="text-base font-semibold leading-none tracking-tight">
            {step.title}
          </h3>
          {showSkipButton && (
            <Button
              variant="ghost"
              size="icon"
              className="h-6 w-6 shrink-0 -mt-1 -mr-2"
              onClick={onClose}
            >
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>

        {/* Content */}
        <p id="tour-description" className="text-sm text-muted-foreground">
          {step.content}
        </p>

        {/* Footer */}
        <div className="mt-4 flex flex-col gap-3">
          <TourProgress
            current={currentIndex}
            total={totalSteps}
            variant={progressVariant}
            onDotClick={onGoTo}
          />

          <TourNavigation
            onNext={onNext}
            onPrevious={onPrevious}
            isFirstStep={isFirstStep}
            isLastStep={isLastStep}
            nextLabel={step.nextLabel}
            previousLabel={step.previousLabel}
            finishLabel={finishLabel}
            nextRoute={step.nextRoute}
            previousRoute={step.previousRoute}
            className="w-full"
          />

          {/* Custom actions */}
          {hasCustomActions && (
            <div className="flex w-full flex-wrap gap-2">
              {customActions.map((action) => (
                <button
                  key={action.key}
                  type="button"
                  onClick={action.onClick}
                  className={action.className}
                >
                  {action.label}
                </button>
              ))}
            </div>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}
